Install
go get github.com/rs/xlog
Copy Logger
You may want to get a copy of the current logger to pass a modified version to a function without touching the original:
l := xlog.FromContext(ctx)
l2 := xlog.Copy(l)
l2.SetField("foo", "bar")
Make sure you copy a request context logger if you plan to use it in a go routine that may still exist after the end of the current request. Contextual loggers are reused after each requests to lower the pressure on the garbage collector. If you would use such a logger in a go routine, you may end up using a logger from another request/context or worse, a nil pointer:
l := xlog.FromContext(ctx)
l2 := xlog.Copy(l)
go func() {
// use the safe copy
l2.Info("something")
}()
Configure Output
By default, output is setup to output debug and info message on STDOUT
and warning and errors to STDERR
. You can easily change this setup.
XLog output can be customized using composable output handlers. Thanks to the LevelOutput, MultiOutput and FilterOutput, it is easy to route messages precisely.
conf := xlog.Config{
Output: xlog.NewOutputChannel(xlog.MultiOutput{
// Send all logs with field type=mymodule to a remote syslog
0: xlog.FilterOutput{
Cond: func(fields map[string]interface{}) bool {
return fields["type"] == "mymodule"
},
Output: xlog.NewSyslogOutput("tcp", "1.2.3.4:1234", "mymodule"),
},
// Setup different output per log level
1: xlog.LevelOutput{
// Send errors to the console
Error: xlog.NewConsoleOutput(),
// Send syslog output for error level
Info: xlog.NewSyslogOutput("", "", ""),
},
}),
})
h = xlog.NewHandler(conf)
Third Party Extensions
Project | Author | Description |
---|---|---|
gRPClog | Hugo González Labrador | An adapter to use xlog as the logger for grpclog. |
xlog-nsq | Olivier Poitrey | An xlog to NSQ output. |
xlog-sentry | trong | An xlog to Sentry output. |