Best practices for logging per http request

agolangf · · 455 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hello, I am developing an http server exposing a JSON API. At the moment, a transaction id is generated at each request and stored in the context.</p> <pre><code>package middlewares import ( &#34;context&#34; &#34;github.com/gin-gonic/gin&#34; &#34;github.com/rs/xid&#34; // TODO Evaluate go.uuid (https://github.com/satori/go.uuid) ) var trxIdKey string = &#34;trxid&#34; func GetTrxId(ctx context.Context) xid.ID { trxId := ctx.Value(trxIdKey) if trxId == nil { panic(&#34;expected the &#34; + trxIdKey + &#34; in context&#34;) } return trxId.(xid.ID) } func TrxId() gin.HandlerFunc { return func(ctx *gin.Context) { // Instantiate a trxid object ctx.Set(trxIdKey, xid.New()) ctx.Next() } } </code></pre> <p>I would like to ask if you have any example of what would be the best practice for logging. The idea is to optionally log the transaction id if present during the whole server execution. I would like avoid the user to manually add it to each log statement.</p> <p>One option would be to create my log struct with logging methods requiring the context, but it doesn&#39;t play well with libraries which offer a way to hook their internal logs, e.g.</p> <pre><code>elastic &#34;gopkg.in/olivere/elastic.v5&#34; elastic.SetErrorLog(logger.Error) </code></pre> <p>Do you have any suggestion?</p> <hr/>**评论:**<br/><br/>nstratos: <pre><p>A good way is to define your HTTP handlers as methods to a type. You can then inject dependencies, like your logger, when initializing the type.</p> <pre><code>type app struct { log Logger } func (app *app) handler(w http.ResponseWriter, r *http.Request) { app.log.Printf(...) } </code></pre> <p>You could also centralize your logging by using helper methods or closures to chain handlers together.</p> <p>If it fits your use case you could potentially use a global logger like <a href="https://github.com/upspin/upspin/blob/master/log/log.go" rel="nofollow">Upspin</a> does.</p> <p>Some good reads:</p> <ul> <li><a href="https://peter.bourgon.org/go-best-practices-2016/#logging-and-instrumentation" rel="nofollow">Go best practices, six years in</a></li> <li><a href="https://blog.golang.org/context" rel="nofollow">https://blog.golang.org/context</a></li> <li><a href="https://medium.com/@cep21/how-to-correctly-use-context-context-in-go-1-7-8f2c0fafdf39" rel="nofollow">How to correctly use context.Context in Go 1.7</a></li> <li><a href="https://github.com/golang/go/wiki/CodeReviewComments#dont-panic" rel="nofollow">Don&#39;t panic</a></li> </ul></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

455 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传