es.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package es
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "net/url"
  8. "time"
  9. "github.com/astaxie/beego/logs"
  10. "github.com/belogik/goes"
  11. )
  12. // NewES return a LoggerInterface
  13. func NewES() logs.Logger {
  14. cw := &esLogger{
  15. Level: logs.LevelDebug,
  16. }
  17. return cw
  18. }
  19. type esLogger struct {
  20. *goes.Connection
  21. DSN string `json:"dsn"`
  22. Level int `json:"level"`
  23. }
  24. // {"dsn":"http://localhost:9200/","level":1}
  25. func (el *esLogger) Init(jsonconfig string) error {
  26. err := json.Unmarshal([]byte(jsonconfig), el)
  27. if err != nil {
  28. return err
  29. }
  30. if el.DSN == "" {
  31. return errors.New("empty dsn")
  32. } else if u, err := url.Parse(el.DSN); err != nil {
  33. return err
  34. } else if u.Path == "" {
  35. return errors.New("missing prefix")
  36. } else if host, port, err := net.SplitHostPort(u.Host); err != nil {
  37. return err
  38. } else {
  39. conn := goes.NewConnection(host, port)
  40. el.Connection = conn
  41. }
  42. return nil
  43. }
  44. // WriteMsg will write the msg and level into es
  45. func (el *esLogger) WriteMsg(when time.Time, msg string, level int) error {
  46. if level > el.Level {
  47. return nil
  48. }
  49. vals := make(map[string]interface{})
  50. vals["@timestamp"] = when.Format(time.RFC3339)
  51. vals["@msg"] = msg
  52. d := goes.Document{
  53. Index: fmt.Sprintf("%04d.%02d.%02d", when.Year(), when.Month(), when.Day()),
  54. Type: "logs",
  55. Fields: vals,
  56. }
  57. _, err := el.Index(d, nil)
  58. return err
  59. }
  60. // Destroy is a empty method
  61. func (el *esLogger) Destroy() {
  62. }
  63. // Flush is a empty method
  64. func (el *esLogger) Flush() {
  65. }
  66. func init() {
  67. logs.Register(logs.AdapterEs, NewES)
  68. }