第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用新功能擴展 log api

如何使用新功能擴展 log api

Go
胡說叔叔 2023-07-26 19:42:42
我將以下代碼與 , 一起使用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"}我不是在談?wù)撌褂?ReportCaller: true,我只是想用我的功能擴展記錄器我該怎么做 ?
查看完整描述

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"

}


查看完整回答
反對 回復(fù) 2023-07-26
  • 1 回答
  • 0 關(guān)注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號