Golang logrus 自定义日志格式

Jackey Golang 1,709 次浏览 , , 没有评论

logrus 仓库地址:https://github.com/sirupsen/logrus

实现代码:

func init() {
    // 配置日志格式
    logrus.SetReportCaller(true)
    logrus.SetFormatter(&MyFormatter{})
    logrus.SetLevel(logrus.DebugLevel)
}

type MyFormatter struct{}

func (m *MyFormatter) Format(entry *logrus.Entry) ([]byte, error) {
    var b *bytes.Buffer
    if entry.Buffer != nil {
        b = entry.Buffer
    } else {
        b = &bytes.Buffer{}
    }
    r, e := json.Marshal(entry.Caller.Entry)
    fmt.Println(string(r), e)
    timestamp := entry.Time.Format("2006-01-02 15:04:05")
    var newLog string
    if entry.Level == logrus.ErrorLevel {
        newLog = fmt.Sprintf("%s \u001B[41m[%s]\u001B[0m %s:%d %s\n", timestamp, entry.Level, entry.Caller.File, entry.Caller.Line, entry.Message)
    } else if entry.Level == logrus.WarnLevel {
        newLog = fmt.Sprintf("%s \u001B[43m[%s]\u001B[0m %s:%d %s\n", timestamp, entry.Level, entry.Caller.File, entry.Caller.Line, entry.Message)
    } else if entry.Level == logrus.InfoLevel {
        newLog = fmt.Sprintf("%s \u001B[46m[%s]\u001B[0m %s:%d %s\n", timestamp, entry.Level, entry.Caller.File, entry.Caller.Line, entry.Message)
    } else {
        newLog = fmt.Sprintf("%s \u001B[47m[%s]\u001B[0m %s:%d %s\n", timestamp, entry.Level, entry.Caller.File, entry.Caller.Line, entry.Message)
    }
    b.WriteString(newLog)
    return b.Bytes(), nil
}

输出日志内容格式:

2023-02-16 09:18:46 [info] /Users/jackey/test/main.go:33 prot:[8081]
2023-02-16 09:18:46 [error] /Users/jackey/test/main.go:34 prot:[8081]

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go