package logruspan import ( "bytes" "encoding/json" "fmt" "gitea.baoapi.com/root/stu_uuos/config" "github.com/sirupsen/logrus" "log" "net/http" "time" ) //setupLogrus 初始化logrus 同时把logrus的logger var 引用到这个common.Logger func setupLogrus(cc config.LogrusHttp) error { logLvl, err := logrus.ParseLevel(cc.LogLvl) if err != nil { return err } Lobj.SetLevel(logLvl) Lobj.SetReportCaller(true) Lobj.SetFormatter(&logrus.JSONFormatter{}) esh := newHttpHook(cc) Lobj.AddHook(esh) return nil } var Lobj *logrus.Logger func LogInitHttp() { cc := *config.GetConfig().LogrusHttp Lobj = logrus.New() err := setupLogrus(cc) if err != nil { log.Fatal(err) } } //esHook 自定义的ES hook type esHook struct { client *http.Client Url string Cont string } //newEsHook 初始化 func newHttpHook(cc config.LogrusHttp) *esHook { //application/json;charset:utf-8; es := &http.Client{} return &esHook{ client: es, Url: cc.Url + "/logger", Cont: "application/json;charset:utf-8;", } } //Fire logrus hook interface 方法 func (hook *esHook) Fire(entry *logrus.Entry) error { go hook.sendHttp(entry) return nil } //Levels logrus hook interface 方法 func (hook *esHook) Levels() []logrus.Level { return []logrus.Level{ logrus.PanicLevel, logrus.FatalLevel, logrus.ErrorLevel, logrus.InfoLevel, } } //sendEs 异步发送日志到es func (hook *esHook) sendHttp(e *logrus.Entry) { defer func() { if r := recover(); r != nil { fmt.Println("send entry to http failed: ", r) } }() ins := map[string]interface{}{} for kk, vv := range e.Data { ins[kk] = vv } ins["time"] = time.Now().Local() ins["level"] = e.Level ins["message"] = e.Message ins["caller"] = fmt.Sprintf("%s:%d %#v", e.Caller.File, e.Caller.Line, e.Caller.Func) bs, err := json.Marshal(ins) br := bytes.NewBuffer(bs) _, err = hook.client.Post(hook.Url, hook.Cont, br) if err != nil { logrus.Println(err) } }