Files
mayfly-go/base/mlog/mlog.go

45 lines
1.1 KiB
Go
Raw Normal View History

2021-03-24 17:18:39 +08:00
package mlog
import (
"fmt"
2021-04-16 15:10:07 +08:00
"path/filepath"
2021-03-24 17:18:39 +08:00
"strings"
"time"
"github.com/sirupsen/logrus"
)
var Log = logrus.New()
func init() {
// customFormatter := new(logrus.TextFormatter)
// customFormatter.TimestampFormat = "2006-01-02 15:04:05.000"
// customFormatter.FullTimestamp = true
Log.SetFormatter(new(LogFormatter))
Log.SetReportCaller(true)
}
type LogFormatter struct{}
func (l *LogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
timestamp := time.Now().Local().Format("2006-01-02 15:04:05.000")
level := entry.Level
logMsg := fmt.Sprintf("%s [%s]", timestamp, strings.ToUpper(level.String()))
// 如果存在调用信息且为error级别以上记录文件及行号
2021-04-16 15:10:07 +08:00
if caller := entry.Caller; caller != nil {
var fp string
if level <= logrus.ErrorLevel {
fp = caller.File
} else {
fp = filepath.Base(caller.File)
}
logMsg = logMsg + fmt.Sprintf(" [%s:%d]", fp, caller.Line)
2021-03-24 17:18:39 +08:00
}
for k, v := range entry.Data {
logMsg = logMsg + fmt.Sprintf(" [%s=%v]", k, v)
}
logMsg = logMsg + fmt.Sprintf(" : %s\n", entry.Message)
return []byte(logMsg), nil
}