<p>AFAIK currently I need to open a file and run log.SetOutput() to that file. Is there a way to not have to copy&paste those lines in every one of my go files?</p>
<hr/>**评论:**<br/><br/>st0n1e: <pre><p>You call this once (err handling not included):</p>
<pre><code>f, _ := os.Open("my.log")
log.SetOutput(f)
</code></pre>
<p>and after this you can use log.Println and so on for every Go file in your whole program because log.SetOutput sets the output of the package global default logger of the log package.</p>
<p>Do the upper logger initialization for example in the first few lines of your main func and it does not matter in which file of your project you call log.Println.</p>
<p>This is fine when you only have one log file. With more log files (e.g. access.log and error.log) you should consider initializing a *log.logger using log.NewLogger and then pass it through your program where it is needed.</p></pre>jeffrallen: <pre><p>Make sure that this is only in package main. In library code, do not mess with the setting of the logger, because your caller knows better than you how he/she wants to get the logs.</p></pre>peterbourgon: <pre><blockquote>
<p>AFAIK currently I need to open a file and run log.SetOutput() to that file.</p>
</blockquote>
<p>If you're doing this, you only need to do it once per process.</p>
<p>But you probably shouldn't be doing this at all. Why are you logging to a file descriptor and not stdout?</p></pre>__crackers__: <pre><blockquote>
<p>Why are you logging to a file descriptor and not stdout?</p>
</blockquote>
<p>Not every program is a web application or system daemon.</p>
<p>Sometimes, you want to write standalone software that is fully-functional on its own. </p></pre>ragefacesmirk: <pre><p>Blasphemy!</p></pre>axlrose___: <pre><p>I want the log to be in a file so I can review it in the future?</p></pre>itachi_amaterasu: <pre><p>Peter is right. This is a common convention espoused by the "12 factor rules" that all your application should do is just log to stdout. The environment should capture the stream and store it in files.</p>
<p>I wrote a tool exactly for this purpose. - <a href="https://github.com/agnivade/funnel" rel="nofollow">https://github.com/agnivade/funnel</a>. Probably that is something that will fit your use case ?</p></pre>earthboundkid: <pre><p>Whatever your using to launch your app (systemd, upstart, supervisor, whatever) should be able to capture stdout to a log file for you.</p></pre>gsempe: <pre><p>This should not be your golang application responsibility but your application environnement with a stream redirection </p></pre>
For logging, is there a way to specify a log file without declaring it in every file?
blov · · 441 次点击这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传