grlogs/logs/es/es.go
2020-04-28 15:27:39 +08:00

106 lines
2.1 KiB
Go

package es
import (
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"time"
"golib.gaore.com/GaoreGo/goes"
"golib.gaore.com/GaoreGo/grlogs/logs"
)
// NewES return a LoggerInterface
func NewES() logs.Logger {
cw := &esLogger{
Level: logs.LevelDebug,
}
return cw
}
type esLogger struct {
*goes.Client
Username string `json:"username"`
Password string `json:"password"`
DSN string `json:"dsn"`
Level int `json:"level"`
IndexName string `json:"index"`
}
// {"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 {
tr := &http.Transport{
ResponseHeaderTimeout: 3 * time.Second,
}
cl := &http.Client{
Transport: tr,
}
conn := goes.NewClient(host, port)
conn.AuthUsername = el.Username
conn.AuthPassword = el.Password
conn.WithHTTPClient(cl)
el.Client = conn
}
return nil
}
// WriteMsg will write the msg and level into es
func (el *esLogger) WriteMsg(when time.Time, msg string, level int, lable string, env string) error {
if level > el.Level {
return nil
}
vals := make(map[string]interface{})
vals["@timestamp"] = when.Format(time.RFC3339)
vals["@msg"] = msg
vals["@level"] = level
vals["level_string"] = logs.GetLevelString(level)
vals["env"] = env
vals["lable"] = lable
if el.IndexName == "" {
return errors.New("index name is empty")
}
d := goes.Document{
Index: fmt.Sprintf("%s-%04d.%02d.%02d", el.IndexName, when.Year(), when.Month(), when.Day()),
Type: "logs",
Fields: vals,
}
_, err := el.Index(d, nil)
return err
}
// Destroy is a empty method
func (el *esLogger) Destroy() {
}
// Flush is a empty method
func (el *esLogger) Flush() {
}
func init() {
logs.Register(logs.AdapterEs, NewES)
}