gpt4 book ai didi

logging - 如何在登录到文件时禁用 logrus 中的字段名称

转载 作者:IT王子 更新时间:2023-10-29 02:12:15 25 4
gpt4 key购买 nike

我在 golang 中使用 logrus 来记录到文件。现在,logrus 正在使用字段名称记录到文件。

time="26-03-2017 03:37:58"level=error msg="不是致命的。一个错误。不会停止执行"

如何删除字段名称,使日志条目变为

错误 26-03-2017 03:37:58 不是致命的。一个错误。不会停止执行

比如它在 stderr 情况下的表现如何?

最佳答案

以下是获取您请求的内容的方法:

package main

import (
log "github.com/sirupsen/logrus"
"fmt"
)

type PlainFormatter struct {
TimestampFormat string
LevelDesc []string
}

func (f *PlainFormatter) Format(entry *log.Entry) ([]byte, error) {
timestamp := fmt.Sprintf(entry.Time.Format(f.TimestampFormat))
return []byte(fmt.Sprintf("%s %s %s\n", f.LevelDesc[entry.Level], timestamp, entry.Message)), nil
}

func main() {
plainFormatter := new(PlainFormatter)
plainFormatter.TimestampFormat = "2006-01-02 15:04:05"
plainFormatter.LevelDesc = []string{"PANC", "FATL", "ERRO", "WARN", "INFO", "DEBG"}
log.SetFormatter(plainFormatter)
log.Errorln("Not fatal. An error. Won't stop execution")
log.Infoln("Just some info")
}
  • 创建 PlainFormatter 结构(带有时间戳格式和级别字段)
  • 创建格式函数/方法(您的结构是接收者)
  • 将 logrus 设置为使用您的自定义格式化程序

输出:

ERRO 2017-07-01 18:22:21 Not fatal. An error. Won't stop execution
INFO 2017-07-01 18:22:21 Just some info

在我的书里Learn Functional Programming in Go在本书的Adding Functionality with Decoration 章节中,您可以看到一个更实际的示例,说明如何操作您的应用程序记录器。

关于logging - 如何在登录到文件时禁用 logrus 中的字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43022607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com