1 回答

TA貢獻1796條經(jīng)驗 獲得超10個贊
一種方法是使用WithFieldsandlogrus.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具有您期望從記錄器獲得的所有方法。您也可以使用該接口logrus.FieldLogger,但如果這樣做,我們將需要堅持該接口上的方法(Log例如沒有方法 - 必須使用信息/錯誤等)。
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"
}
- 1 回答
- 0 關(guān)注
- 150 瀏覽
添加回答
舉報