Trouble with a logging function not writing to the file

agolangf · · 388 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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&#39;m new to go and I&#39;m sure I&#39;m doing something obviously wrong.</p> <p>lib/Logger</p> <pre><code>func Logger() *log.Logger { f, err := os.OpenFile(&#34;log.txt&#34;, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { log.Fatal(err) } logger := log.New(f, &#34;test&#34;, 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 &#34;defer f.Close()&#34; 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&#39;re closing the file at the end of the <code>Logger()</code> function, and you can&#39;t write to a closed file.</p> <p>Edit: Whoops; I&#39;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&#39;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

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