<p>I'm working on a library that I'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'm leaning towards 3 (heavy) or 1 (but levels!). I haven't found any good examples how others have handled it. Suggestions?</p>
<hr/>**评论:**<br/><br/>bmurphy1976: <pre><p>Here'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, "cancelled:", 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 'incidents', in my opinion, you need 1+3 (both, not one or the other).</p></pre>anacrolix: <pre><p>2. Don't expose leveling crap. I don't care about your levels. I just want to see messages if it's not working, and will suppress anything uninteresting myself.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传