8

Is there a way in go language to log to multiple output in different levels?.

I want to have a program that logs to stdout in Info level and to a file in debug level with timestamp at the same time.

Like every time I code:

log.Debug("Entering some func")
res := func()
log.Infof("Result was: %s", res)

I can see the console prints:

Result was: Successful

And a file with:

2015-03-26T01:27:38-04:00 [DEBU]: Entering some func
2015-03-26T01:27:38-04:00 [INFO]: Result was: Successful

I use logrus and glog, but can't find this functionallity. Is there another package or something I can code?

0

4 Answers 4

14

Found this while looking for a way to log to multiple destinations. If that is all you need and aren't worried about the log level the simplest way is to use an io.Multiwriter:

multi := io.MultiWriter(file, os.Stdout)
log.SetOutput(multi)
Sign up to request clarification or add additional context in comments.

1 Comment

This is the best answer since it can be added to any existing code that uses the standard log library
8

Go-logging supports different logging backends like file, syslog etc. Multiple backends can be set with different log levels per backend and logger. Example over here.

Lumberjack can also be used with this for writing logs to rolling files. Here is an example.

Comments

1

If you use the go-logging library you can set up two "backends" which will write to stdout and to a file.

I'd copy some code here, but the example on the wiki does exactly what you want.

Comments

1

mw := io.MultiWriter(os.Stdout, logFile) logrus.SetOutput(mw)

from here https://github.com/Sirupsen/logrus/issues/230

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.