Could log.setoutput output to both console and log file?

8,555 views
Skip to first unread message

dlin

unread,
May 30, 2011, 8:47:34 PM5/30/11
to golang-nuts
I know how to write to log file, but, how to write output to
console(stderr) and log file at the same time?

Steven

unread,
May 30, 2011, 9:01:56 PM5/30/11
to dlin, golang-nuts
On Mon, May 30, 2011 at 8:47 PM, dlin <dlin.tw@gmail.com> wrote:
I know how to write to log file, but, how to write output to
console(stderr) and log file at the same time?


You can use os.Stderr as the Writer for stderr.

dlin

unread,
May 30, 2011, 11:35:51 PM5/30/11
to golang-nuts
Thanks,

But, I still don't know how to separate to behavior of normal message
and fatal message.

log.Println just send to logf.
log.Fatalln send to both console and logf.

here is my code.

logf, err := os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE,
0640)
if err != nil {
log.Fatalln(err)
}
log.SetOutput(io.MultiWriter(logf, os.Stdout))


On 5月31日, 上午9時01分, Steven <steven...@gmail.com> wrote:

Jessta

unread,
May 30, 2011, 11:45:39 PM5/30/11
to dlin, golang-nuts
On Tue, May 31, 2011 at 1:35 PM, dlin <dli...@gmail.com> wrote:
> Thanks,
>
> But, I still don't know how to separate to behavior of normal message
> and fatal message.
>
> log.Println just send to logf.
> log.Fatalln send to both console and logf.

You'll have to create another log.Logger
http://golang.org/pkg/log/#Logger.New

> here is my code.
>
>        logf, err := os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE,
> 0640)
>        if err != nil {
>            log.Fatalln(err)
>        }

log.SetOutput(logf)
mylogger := log.New(io.MultiWriter(logf,os.Stdout)
log.Println("goes to logf")
mylogger.Fatalln("goes to stdout and logf")

--
=====================
http://jessta.id.au

Kyle Lemons

unread,
Sep 4, 2012, 2:50:51 PM9/4/12
to mkal...@gmail.com, golan...@googlegroups.com, dlin, jes...@jessta.id.au
If you have specialized logging requirements along those lines, you can always try out log4go (full disclosure: mine).

On Mon, Sep 3, 2012 at 10:01 AM, <mkal...@gmail.com> wrote:
Is there a nice way to do the same, but have different logging parameters for each output?  For example, I'd like the data logged to file to have date and timestamps, while the version written to stdout to be bare, just the messages themselves?  I suspect there is no clever way to do that, short of writing a module which specifically does this itself...
Reply all
Reply to author
Forward
0 new messages