高热共公日志库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

112 lines
2.3 KiB

  1. package es
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. "net/url"
  9. "time"
  10. "golib.gaore.com/GaoreGo/goes"
  11. "golib.gaore.com/GaoreGo/grlogs/logs"
  12. )
  13. // NewES return a LoggerInterface
  14. func NewES() logs.Logger {
  15. cw := &esLogger{
  16. Level: logs.LevelDebug,
  17. }
  18. return cw
  19. }
  20. type esLogger struct {
  21. *goes.Client
  22. Username string `json:"username"`
  23. Password string `json:"password"`
  24. DSN string `json:"dsn"`
  25. Level int `json:"level"`
  26. IndexName string `json:"index"`
  27. }
  28. // {"dsn":"http://localhost:9200/","level":1}
  29. func (el *esLogger) Init(jsonconfig string) error {
  30. err := json.Unmarshal([]byte(jsonconfig), el)
  31. if err != nil {
  32. return err
  33. }
  34. if el.DSN == "" {
  35. return errors.New("empty dsn")
  36. } else if u, err := url.Parse(el.DSN); err != nil {
  37. return err
  38. } else if u.Path == "" {
  39. return errors.New("missing prefix")
  40. } else if host, port, err := net.SplitHostPort(u.Host); err != nil {
  41. return err
  42. } else {
  43. tr := &http.Transport{
  44. ResponseHeaderTimeout: 3 * time.Second,
  45. }
  46. cl := &http.Client{
  47. Transport: tr,
  48. }
  49. conn := goes.NewClient(host, port)
  50. conn.AuthUsername = el.Username
  51. conn.AuthPassword = el.Password
  52. conn.WithHTTPClient(cl)
  53. el.Client = conn
  54. }
  55. return nil
  56. }
  57. // WriteMsg will write the msg and level into es
  58. func (el *esLogger) WriteMsg(when time.Time, msg string, level int, lable string, env string) error {
  59. if level > el.Level {
  60. return nil
  61. }
  62. vals := make(map[string]interface{})
  63. vals["@timestamp"] = when.Format(time.RFC3339)
  64. vals["@msg"] = msg
  65. vals["@level"] = level
  66. vals["level_string"] = logs.GetLevelString(level)
  67. vals["env"] = env
  68. vals["lable"] = lable
  69. vals["hostname"] = GetHostname()
  70. vals["working_idr"] = Getwd()
  71. vals["home_dir"] = GetUserHomename()
  72. vals["hardware_addr"] = GetCurrentInterface().HardwareAddr
  73. vals["client_addrs"] = GetCurrentInterfaceAddrs()
  74. if el.IndexName == "" {
  75. return errors.New("index name is empty")
  76. }
  77. d := goes.Document{
  78. Index: fmt.Sprintf("%s-%04d.%02d.%02d", el.IndexName, when.Year(), when.Month(), when.Day()),
  79. Type: "logs",
  80. Fields: vals,
  81. }
  82. _, err := el.Index(d, nil)
  83. return err
  84. }
  85. // Destroy is a empty method
  86. func (el *esLogger) Destroy() {
  87. }
  88. // Flush is a empty method
  89. func (el *esLogger) Flush() {
  90. }
  91. func init() {
  92. logs.Register(logs.AdapterEs, NewES)
  93. }