<p>I have a function that returns a pointer to a log.Logger. Within the function I can log to the file just fine, but when I invoke the function from the main app, and call the Println method, nothing seems to happen (it does create the file though).</p>
<p>I'm new to go and I'm sure I'm doing something obviously wrong.</p>
<p>lib/Logger</p>
<pre><code>func Logger() *log.Logger {
f, err := os.OpenFile("log.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
logger := log.New(f, "test", 0)
defer f.Close()
return logger
}
</code></pre>
<p>main</p>
<pre><code>func status(w http.ResponseWriter, r *http.Request) {
logger := lib.Logger()
logger.Println(r.RemoteAddr)
...
}
</code></pre>
<p>Any help would be appreciated!</p>
<hr/>**评论:**<br/><br/>GopherFromHell: <pre><p>the line with the "defer f.Close()" is your culprit.</p></pre>potatofloss: <pre><p>I could have sworn I tried removing that!</p>
<p>Thanks!</p></pre>Fwippy: <pre><p>You're closing the file at the end of the <code>Logger()</code> function, and you can't write to a closed file.</p>
<p>Edit: Whoops; I'm slow.</p></pre>potatofloss: <pre><p>That certainly makes sense ; )</p>
<p>Is there a way to close the file handle without having to call os.File.Close in every function I'm registering with http.HandleFunc? Ideally within the Logger function?</p></pre>barsonme: <pre><p>Keep the file permanently open and only close it when you close your app
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传