白衣染霜花
一种方法是使用WithFieldsandlogrus.Fields像这样:package mainimport ( "github.com/sirupsen/logrus" "os" "runtime" "strconv" "strings")func main() { lgr().Log(logrus.InfoLevel, "info")}func lgr() *logrus.Entry { pc, file, line, ok := runtime.Caller(1) if !ok { panic("Could not get context info for logger!") } filename := file[strings.LastIndex(file, "/")+1:] + ":" + strconv.Itoa(line) funcname := runtime.FuncForPC(pc).Name() fn := funcname[strings.LastIndex(funcname, ".")+1:] loggerImpl := &logrus.Logger{ Out: os.Stdout, Hooks: nil, Formatter: &logrus.JSONFormatter{ TimestampFormat: "2006-01-02 15:04:05", PrettyPrint: true, }, Level: logrus.InfoLevel, ExitFunc: nil, } return loggerImpl.WithFields(logrus.Fields{ "file": filename, "function": fn, })}上面的代码*logrus.Entry具有您期望从记录器获得的所有方法。您也可以使用该接口logrus.FieldLogger,但如果这样做,我们将需要坚持该接口上的方法(Log例如没有方法 - 必须使用信息/错误等)。package mainimport ( "github.com/sirupsen/logrus" "os" "runtime" "strconv" "strings")func main() { lgr().Infoln("Hello world")}func lgr() logrus.FieldLogger { pc, file, line, ok := runtime.Caller(1) if !ok { panic("Could not get context info for logger!") } filename := file[strings.LastIndex(file, "/")+1:] + ":" + strconv.Itoa(line) funcname := runtime.FuncForPC(pc).Name() fn := funcname[strings.LastIndex(funcname, ".")+1:] loggerImpl := &logrus.Logger{ Out: os.Stdout, Hooks: nil, Formatter: &logrus.JSONFormatter{ TimestampFormat: "2006-01-02 15:04:05", PrettyPrint: true, }, Level: logrus.InfoLevel, ExitFunc: nil, } return loggerImpl.WithFields(logrus.Fields{ "file": filename, "function": fn, })}输出:{ "file": "main.go:12", "function": "main", "level": "info", "msg": "Hello world", "time": "2019-10-07 01:24:10"}