1 回答

TA貢獻1794條經驗 獲得超8個贊
您可以使用文件、函數和行信息包裝記錄器,然后使用它們。
這是一個例子:
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 關注
- 113 瀏覽
添加回答
舉報