haiwai-grlogs/logs/es/es.go

112 lines
2.3 KiB
Go
Raw Normal View History

package es
import (
"encoding/json"
"errors"
"fmt"
"net"
2020-04-28 14:32:56 +08:00
"net/http"
"net/url"
"time"
2020-04-28 14:32:56 +08:00
"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
2020-04-28 15:27:39 +08:00
Username string `json:"username"`
Password string `json:"password"`
2020-04-28 14:32:56 +08:00
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 {
2020-04-28 14:32:56 +08:00
tr := &http.Transport{
ResponseHeaderTimeout: 3 * time.Second,
}
cl := &http.Client{
Transport: tr,
}
conn := goes.NewClient(host, port)
2020-04-28 15:27:39 +08:00
conn.AuthUsername = el.Username
conn.AuthPassword = el.Password
2020-04-28 14:32:56 +08:00
conn.WithHTTPClient(cl)
el.Client = conn
}
return nil
}
// WriteMsg will write the msg and level into es
2020-04-28 15:27:39 +08:00
func (el *esLogger) WriteMsg(when time.Time, msg string, level int, lable string, env string) error {
2020-04-28 17:17:21 +08:00
if level > el.Level {
return nil
}
vals := make(map[string]interface{})
vals["@timestamp"] = when.Format(time.RFC3339)
vals["@msg"] = msg
2020-04-28 14:32:56 +08:00
vals["@level"] = level
2020-04-28 15:27:39 +08:00
vals["level_string"] = logs.GetLevelString(level)
vals["env"] = env
vals["lable"] = lable
2020-04-28 17:17:21 +08:00
vals["hostname"] = GetHostname()
vals["working_idr"] = Getwd()
vals["home_dir"] = GetUserHomename()
vals["hardware_addr"] = GetCurrentInterface().HardwareAddr
vals["client_addrs"] = GetCurrentInterfaceAddrs()
2020-04-28 15:27:39 +08:00
if el.IndexName == "" {
return errors.New("index name is empty")
}
d := goes.Document{
2020-04-28 14:32:56 +08:00
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)
}