logs support elasticsearch adapter
Showing
1 changed file
with
76 additions
and
0 deletions
logs/es/es.go
0 → 100644
| 1 | package es | ||
| 2 | |||
| 3 | import ( | ||
| 4 | "encoding/json" | ||
| 5 | "errors" | ||
| 6 | "fmt" | ||
| 7 | "net" | ||
| 8 | "net/url" | ||
| 9 | "time" | ||
| 10 | |||
| 11 | "github.com/astaxie/beego/logs" | ||
| 12 | "github.com/belogik/goes" | ||
| 13 | ) | ||
| 14 | |||
| 15 | func NewES() logs.LoggerInterface { | ||
| 16 | cw := &esLogger{ | ||
| 17 | Level: logs.LevelDebug, | ||
| 18 | } | ||
| 19 | return cw | ||
| 20 | } | ||
| 21 | |||
| 22 | type esLogger struct { | ||
| 23 | *goes.Connection | ||
| 24 | DSN string `json:"dsn"` | ||
| 25 | Level int `json:"level"` | ||
| 26 | } | ||
| 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 | conn := goes.NewConnection(host, port) | ||
| 44 | el.Connection = conn | ||
| 45 | } | ||
| 46 | return nil | ||
| 47 | } | ||
| 48 | |||
| 49 | func (el *esLogger) WriteMsg(msg string, level int) error { | ||
| 50 | if level > el.Level { | ||
| 51 | return nil | ||
| 52 | } | ||
| 53 | t := time.Now() | ||
| 54 | vals := make(map[string]interface{}) | ||
| 55 | vals["@timestamp"] = t.Format(time.RFC3339) | ||
| 56 | vals["@msg"] = msg | ||
| 57 | d := goes.Document{ | ||
| 58 | Index: fmt.Sprintf("%04d.%02d.%02d", t.Year(), t.Month(), t.Day()), | ||
| 59 | Type: "logs", | ||
| 60 | Fields: vals, | ||
| 61 | } | ||
| 62 | _, err := el.Index(d, nil) | ||
| 63 | return err | ||
| 64 | } | ||
| 65 | |||
| 66 | func (el *esLogger) Destroy() { | ||
| 67 | |||
| 68 | } | ||
| 69 | |||
| 70 | func (el *esLogger) Flush() { | ||
| 71 | |||
| 72 | } | ||
| 73 | |||
| 74 | func init() { | ||
| 75 | logs.Register("es", NewES) | ||
| 76 | } |
-
Please register or sign in to post a comment