我将以下代码与 logrus
一起使用,我想扩展它,即
在每次使用这个 logrus 日志时,它会默认添加 function
和 file
但它不起作用
我得到了
{
"level": "info",
"msg": "info",
"time": "2019-10-06 17:14:25"
}
我要
{
"file": “myfile.go",
"func": “myfunc:95",
"level": "info",
"msg": "info",
"time": "2019-10-06 17:17:53"
}
我不是在谈论使用 ReportCaller:是的,我只是想用我的函数扩展记录器
我该怎么做 ?
这就是我尝试的
package main
import (
"os"
"runtime"
"strconv"
"strings"
"github.com/sirupsen/logrus"
)
func main() {
lgr().Log(logrus.InfoLevel,"info")
}
func lgr() *logrus.Logger {
loggerImpl := &logrus.Logger{
Out: os.Stdout,
Hooks: nil,
Formatter: &logrus.JSONFormatter{
TimestampFormat: "2006-01-02 15:04:05",
CallerPrettyfier: func(f *runtime.Frame) (string, string) {
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:]
return filename, fn
},
PrettyPrint: true,
},
Level: logrus.InfoLevel,
ExitFunc: nil,
}
return loggerImpl
}
最佳答案
一种方法是使用 WithFields
和 logrus.Fields
像这样:
package main
import (
"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
具有您期望从记录器获得的所有方法。也可以使用接口(interface)logrus.FieldLogger
但如果我们这样做,我们将需要坚持该接口(interface)上的方法,(例如没有 Log
方法 - 必须使用 Info/Error 等)。package main
import (
"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"
}
关于go - 如何使用新功能扩展日志 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58260137/