Logging in libraries, what's the best practice?

polaris · · 570 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;m working on a library that I&#39;m going to make public that does a lot of http interactions. Many of the possible failures are recoverable within the library but the user of the library may want to know about them. How should I handle this? Options I can think of:</p> <ol> <li>Use the standard library logger</li> <li>Let the user pass in a logger, conform to standard library</li> <li>Make my own logging interface with adapters</li> <li>Make a string channel that gets passed around</li> </ol> <p>I&#39;m leaning towards 3 (heavy) or 1 (but levels!). I haven&#39;t found any good examples how others have handled it. Suggestions?</p> <hr/>**评论:**<br/><br/>bmurphy1976: <pre><p>Here&#39;s what I do:</p> <pre><code>type Logger func(...interface{}) var debugLog Logger = nil func SetDebugLogger(logger Logger) { debugLog = logger } var errorLog Logger = nil func SetErrorLogger(logger Logger) { errorLog = logger } </code></pre> <p>And I use it like this:</p> <pre><code>if errorLog != nil { errorLog(r, &#34;cancelled:&#34;, result.Err) } </code></pre> <p>Works great. Binding it to the standard logging library is as easy as doing this:</p> <pre><code>library.SetDebugLogger(log.Printf) library.SetErrorLogger(log.Errorf) </code></pre> <p>And of course you can bind it to any method from any other logging library as long as they have the same signature, or you could write a simple wrapper method to adapt the function as appropriate.</p></pre>Rhaseven7h: <pre><p>What we do in our packages for consumption by other teams, is provide a logger by default and provide a way to set a custom one if the caller needs it (log.Logger), using custom logger types is frowned upon. But given your use case, yes, a buffered channel seems like the way to go to notify of runtime &#39;incidents&#39;, in my opinion, you need 1+3 (both, not one or the other).</p></pre>anacrolix: <pre><p>2. Don&#39;t expose leveling crap. I don&#39;t care about your levels. I just want to see messages if it&#39;s not working, and will suppress anything uninteresting myself.</p></pre>

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

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