91 lines
1.5 KiB
Go
91 lines
1.5 KiB
Go
package logger
|
|
|
|
import (
|
|
"context"
|
|
"github.com/sirupsen/logrus"
|
|
"os"
|
|
)
|
|
|
|
var l *Logx
|
|
|
|
var TraceIdKey = "trace_id"
|
|
|
|
type Logx struct {
|
|
*logrus.Logger
|
|
ctx *context.Context
|
|
}
|
|
|
|
type LogField struct {
|
|
Key string
|
|
Value interface{}
|
|
}
|
|
|
|
func init() {
|
|
ctx := context.Background()
|
|
l = &Logx{
|
|
Logger: logrus.New(),
|
|
ctx: &ctx,
|
|
}
|
|
|
|
l.SetFormatter(&logrus.JSONFormatter{TimestampFormat: "2006-01-02 15:04:05"})
|
|
// 设置输出
|
|
l.SetOutput(os.Stdout)
|
|
|
|
// 设置最低loglevel
|
|
l.SetLevel(logrus.DebugLevel)
|
|
|
|
l.SetReportCaller(true)
|
|
}
|
|
|
|
func WithContext(ctx context.Context) {
|
|
l.ctx = &ctx
|
|
}
|
|
|
|
func Field(key string, value interface{}) *LogField {
|
|
return &LogField{Key: key, Value: value}
|
|
}
|
|
|
|
func Info(msg string, fields ...*LogField) {
|
|
e := newEntry(fields...)
|
|
e.Info(msg)
|
|
}
|
|
|
|
func Error(msg string, fields ...*LogField) {
|
|
e := newEntry(fields...)
|
|
e.Error(msg)
|
|
}
|
|
|
|
func Debug(msg string, fields ...*LogField) {
|
|
e := newEntry(fields...)
|
|
e.Debug(msg)
|
|
}
|
|
|
|
func Warning(msg string, fields ...*LogField) {
|
|
e := newEntry(fields...)
|
|
e.Warning(msg)
|
|
}
|
|
|
|
func newEntry(fields ...*LogField) *logrus.Entry {
|
|
e := logrus.NewEntry(l.Logger)
|
|
traceId, ok := (*l.ctx).Value(TraceIdKey).(string)
|
|
if ok {
|
|
e = e.WithField("trace_id", traceId)
|
|
}
|
|
for _, field := range fields {
|
|
e = e.WithField(field.Key, field.Value)
|
|
}
|
|
return e
|
|
}
|
|
|
|
func Errorf(format string, args ...interface{}) {
|
|
l.Errorf(format, args)
|
|
}
|
|
|
|
func Fatal(args ...interface{}) {
|
|
l.Fatal(args)
|
|
}
|
|
|
|
func Println(args ...interface{}) {
|
|
l.Println(args)
|
|
}
|