1 回答
TA贡献1794条经验 获得超7个赞
您可以使用文件、函数和行信息包装记录器,然后使用它们。
这是一个例子:
package main
import (
"os"
"runtime"
"strconv"
"strings"
log "github.com/sirupsen/logrus"
)
func init() {
log.SetFormatter(&log.JSONFormatter{})
log.SetOutput(os.Stdout)
}
func logger() *log.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:]
return log.WithField("file", filename).WithField("function", fn)
}
func test() {
logger().Info("Testing...")
}
func main() {
logger().Info("Testing...")
test()
}
输出:
{"file":"prog.go:34","function":"main","level":"info","msg":"Testing...","time":"2009-11-10T23:00:00Z"}
{"file":"prog.go:30","function":"test","level":"info","msg":"Testing...","time":"2009-11-10T23:00:00Z"}
- 1 回答
- 0 关注
- 89 浏览
添加回答
举报