How to implement level based logging in golang?

2019-03-12 04:09发布

Is there any good wrapper available for level based logging in golang? If not, how should I go about implementing one myself?

What I want is pretty simple. I want a few functions e.g.

log.Error()
log.Info()

etc that display their outputs to stdout as well as save these in a log file (based on the level given to the program as commandline argument). How do I implement this wrapper?

标签: logging go
8条回答
Viruses.
2楼-- · 2019-03-12 04:27

https://github.com/hashicorp/logutils I found this to be very easy to use and you don't even need to change the method calls to log.Printf of the std library.

查看更多
smile是对你的礼貌
3楼-- · 2019-03-12 04:28

Uber-go/Zap: Fast, structured, leveled logging in Go

查看更多
▲ chillily
4楼-- · 2019-03-12 04:28

I am working with rlog at the moment and like their approach. The code looks good, simplistic and sufficiently documented.

What convinced me:

  • no external dependencies
  • i can use rlog.Info() anywhere without passing around references
  • good usage of environment variables
  • arbitrary number of trace levels e.g. rlog.Trace(4, "foo")
查看更多
smile是对你的礼貌
5楼-- · 2019-03-12 04:36

Some more suggestions, now that the existing answers are quite old:

查看更多
beautiful°
6楼-- · 2019-03-12 04:37

I have added logging level support to the built-in Go log package. You can find my code here:

https://github.com/gologme/log

In addition to adding support for Info, Warn, and Debug, users can also define their own arbitrary logging levels. Logging levels are enabled and disabled individually. This means you can turn on Debug logs without also getting everything else.

查看更多
闹够了就滚
7楼-- · 2019-03-12 04:44

stdlog fits exactly your requirements:

log := stdlog.GetFromFlags()
log.Info("Connecting to the server...")
log.Errorf("Connection failed: %q", err)
查看更多
登录 后发表回答