在Go中,可以通过包装日志记录器来在每个请求的消息中添加特定信息。

huangapple go评论94阅读模式
英文:

Go - Wrap logger in order to add a specific information in each message of a request

问题

我正在开发一个HTTP API项目,有一个功能我想实现,但是我还没有找到方法。在我的情况下,我在请求中发送一个事务ID,我想要做的是获取这个事务ID并在日志记录器中使用它,在当前请求的每个日志条目中添加这个信息。我想这样做是为了在发生问题时更好地过滤我的日志以检索信息。

例如,我的事务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"

这是我想在我的日志中拥有的信息。

所以,我想知道是否有一种方法可以将日志记录器作为单例使用,并在每次调用日志记录器时添加信息。

希望我在这个问题中提供了足够的细节。

谢谢。

英文:

I'm working on a project of an http api and there is a thing I want to implement but I have not find the way to do it.
So, in my case I send in a request a transaction id, and the thin I want to do is to get this transaction id and use it in the logger, add this information in each log entry of the current request. I want to do this to have a better filtering of my logs when I want to retrieve information if some issue happens.

For example my transaction id is 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 kind of information I want to have in my logs.

So instead injecting the transaction id in each log call, I was wondering if there is a way to use the logger as a singleton and add the information each time the logger is called.

I hope I provided enough details in this issue.

thanks.

答案1

得分: 2

在日志记录器中添加事务ID前缀。标准的Go日志记录器提供了多种方法来实现。一个例子是log.New()方法。

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

GetLogger函数将返回一个日志记录器,它会在每条日志中添加事务ID前缀。

英文:

Prefix your transaction id in logger. Standard go logger provide many ways to do it. An example is log.New() method.

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

GetLogger will give you a logger that will prefix your transactionID in every log.

答案2

得分: 0

以下是从我的答案中复制的一个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()))

请注意,这是一个用于Gin框架的中间件示例,用于记录HTTP请求和响应的日志。你需要确保已经导入了相应的包,并将其与你的Gin引擎实例一起使用。

英文:

here's a logrus solution copied from my answer here, put this at the top of your middleware chain, and update the fields to grab the request's 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()))

huangapple
  • 本文由 发表于 2016年8月19日 23:46:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/39043108.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定