高热共公日志库
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.

94 lines
1.7 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. DSN string `json:"dsn"`
  23. Level int `json:"level"`
  24. IndexName string `json:"index"`
  25. }
  26. // {"dsn":"http://localhost:9200/","level":1}
  27. func (el *esLogger) Init(jsonconfig string) error {
  28. err := json.Unmarshal([]byte(jsonconfig), el)
  29. if err != nil {
  30. return err
  31. }
  32. if el.DSN == "" {
  33. return errors.New("empty dsn")
  34. } else if u, err := url.Parse(el.DSN); err != nil {
  35. return err
  36. } else if u.Path == "" {
  37. return errors.New("missing prefix")
  38. } else if host, port, err := net.SplitHostPort(u.Host); err != nil {
  39. return err
  40. } else {
  41. tr := &http.Transport{
  42. ResponseHeaderTimeout: 3 * time.Second,
  43. }
  44. cl := &http.Client{
  45. Transport: tr,
  46. }
  47. conn := goes.NewClient(host, port)
  48. conn.WithHTTPClient(cl)
  49. el.Client = conn
  50. }
  51. return nil
  52. }
  53. // WriteMsg will write the msg and level into es
  54. func (el *esLogger) WriteMsg(when time.Time, msg string, level int) error {
  55. if level > el.Level {
  56. return nil
  57. }
  58. vals := make(map[string]interface{})
  59. vals["@timestamp"] = when.Format(time.RFC3339)
  60. vals["@msg"] = msg
  61. vals["@level"] = level
  62. d := goes.Document{
  63. Index: fmt.Sprintf("%s-%04d.%02d.%02d", el.IndexName, when.Year(), when.Month(), when.Day()),
  64. Type: "logs",
  65. Fields: vals,
  66. }
  67. _, err := el.Index(d, nil)
  68. return err
  69. }
  70. // Destroy is a empty method
  71. func (el *esLogger) Destroy() {
  72. }
  73. // Flush is a empty method
  74. func (el *esLogger) Flush() {
  75. }
  76. func init() {
  77. logs.Register(logs.AdapterEs, NewES)
  78. }