我在golang中使用logrus来登录文件。现在,logrus正在使用字段名称记录到文件。
即
time="26-03-2017 03:37:58" level=error msg="Not fatal. An error. Won't stop execution"
如何删除字段名称以使日志条目变为
ERRO 26-03-2017 03:37:58 Not fatal. An error. Won't stop execution
就像stderr的情况一样?
答案 0 :(得分:0)
您需要编写一个自定义格式化程序,仅发出您想要查看的字段。
logrus readme中有一个例子:
type MyJSONFormatter struct {
}
log.SetFormatter(new(MyJSONFormatter))
func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
// Note this doesn't include Time, Level and Message which are available on
// the Entry. Consult `godoc` on information about those fields or read the
// source of the official loggers.
serialized, err := json.Marshal(entry.Data)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
return append(serialized, '\n'), nil
}
答案 1 :(得分:0)
以下是如何获得您的要求:
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")
}
输出:
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一书中,您可以看到一个更实用的示例,说明如何在添加带装饰功能章节中操作应用程序记录器。