Go - Wrap logger to add specific information to each request message

I am working on an http api project and there is a thing that I want to implement, but I have not found a way to do this. Thus, in my case, I send the request a transaction ID, and the thin one I want to do is get this transaction ID and use it in the registrar, add this information to each log entry of the current request. I want to do this in order to better filter my logs when I want to receive information if there is any problem.

For example, my transaction ID foo: api | [GIN] 2016/08/19 - 13:00:37 | 201 | 30.791855ms | 192.168.99.1:63922 | POST /v1/my/endpoint api | time="2016-08-19T13:00:39Z" level=info msg="Authenticated API user: tests" transactionId="foo" api | time="2016-08-19T13:00:39Z" level=debug msg="SQL query" args=25 query=" SELECT id, created, information1, information2 FROM mydb.mytable WHERE id = ?; " transactionId="foo" This is the information that I want to have in my logs.

Therefore, instead of entering a transaction identifier in each call to the log, I was wondering if there was a way to use the logger as a singleton object and add information every time the log is called.

Hope I have provided enough details in this release.

thank.

+4
source share
2 answers

Transaction ID prefix in the log. The standard gologger provides many ways to do this. An example is the log.New () method.

func GetLogger(transactionID string) *log.Logger {
    return log.New(os.Stdout, fmt.Sprintf("[transactionId = %s ] ", transactionID),
         log.Lshortfile)
}

GetLogger will provide you with a logger that will prefix your transaction ID in each log.

+2
source

logrus, , , txid.

func Logrus(logger *logrus.Logger) gin.HandlerFunc {
    return func(c *gin.Context) {
        start := time.Now().UTC()
        path := c.Request.URL.Path
        c.Next()
        end := time.Now().UTC()
        latency := end.Sub(start)
        logger.WithFields(logrus.Fields{
            "status":     c.Writer.Status(),
            "method":     c.Request.Method,
            "path":       path,
            "ip":         c.ClientIP(),
            "duration":   latency,
            "user_agent": c.Request.UserAgent(),
        }).Info()
    }
}
GinEngine.Use(Logger(logrus.StandardLogger()))
0

Source: https://habr.com/ru/post/1651814/


All Articles