Files
mayfly-go/base/mlog/mlog.go
2021-04-16 15:10:07 +08:00

45 lines
1.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package mlog
import (
"fmt"
"path/filepath"
"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级别以上记录文件及行号
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)
}
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
}