1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-18 16:20:54 +00:00
Beego/logs/es/es.go

81 lines
1.5 KiB
Go
Raw Normal View History

2015-06-12 16:25:48 +00:00
package es
import (
"encoding/json"
"errors"
"fmt"
"net"
"net/url"
"time"
"github.com/astaxie/beego/logs"
"github.com/belogik/goes"
)
2015-09-11 15:08:24 +00:00
// NewES return a LoggerInterface
func NewES() logs.Logger {
2015-06-12 16:25:48 +00:00
cw := &esLogger{
Level: logs.LevelDebug,
}
return cw
}
type esLogger struct {
*goes.Connection
DSN string `json:"dsn"`
Level int `json:"level"`
}
// {"dsn":"http://localhost:9200/","level":1}
func (el *esLogger) Init(jsonconfig string) error {
err := json.Unmarshal([]byte(jsonconfig), el)
if err != nil {
return err
}
if el.DSN == "" {
return errors.New("empty dsn")
} else if u, err := url.Parse(el.DSN); err != nil {
return err
} else if u.Path == "" {
return errors.New("missing prefix")
} else if host, port, err := net.SplitHostPort(u.Host); err != nil {
return err
} else {
conn := goes.NewConnection(host, port)
el.Connection = conn
}
return nil
}
2015-09-11 15:08:24 +00:00
// WriteMsg will write the msg and level into es
2016-01-23 08:24:58 +00:00
func (el *esLogger) WriteMsg(when time.Time, msg string, level int) error {
2015-06-12 16:25:48 +00:00
if level > el.Level {
return nil
}
2016-01-23 08:24:58 +00:00
2015-06-12 16:25:48 +00:00
vals := make(map[string]interface{})
2016-01-23 08:24:58 +00:00
vals["@timestamp"] = when.Format(time.RFC3339)
2015-06-12 16:25:48 +00:00
vals["@msg"] = msg
d := goes.Document{
2016-01-23 08:24:58 +00:00
Index: fmt.Sprintf("%04d.%02d.%02d", when.Year(), when.Month(), when.Day()),
2015-06-12 16:25:48 +00:00
Type: "logs",
Fields: vals,
}
_, err := el.Index(d, nil)
return err
}
2015-09-11 15:08:24 +00:00
// Destroy is a empty method
2015-06-12 16:25:48 +00:00
func (el *esLogger) Destroy() {
}
2015-09-11 15:08:24 +00:00
// Flush is a empty method
2015-06-12 16:25:48 +00:00
func (el *esLogger) Flush() {
}
func init() {
2016-03-24 10:21:52 +00:00
logs.Register(logs.AdapterEs, NewES)
2015-06-12 16:25:48 +00:00
}