I am using logrus in a Go app. I believe this question is applicable to any other logging package (which doesn't offer external file based configuration) as well.
logrus provides functions to setup various configuration, e.g. SetOutput, SetLevel etc.
Like any other application I need to do logging from multiple source files/packages, it seems you need to setup these options in each file with logrus.
Is there any way to setup these options once somewhere in a central place to be shared all over the application. That way if I have to make logging level change I can do it in one place and applies to all the components of the app.
This is the solution that I arrived at for my application that allows adding of fields to the logging context. It does have a small performance impact due to the copying of context base fields.
You don't need to set these options in each file with Logrus.
You can import Logrus as
log
:Then functions like
log.SetOutput()
are just functions and modify the global logger and apply to any file that includes this import.You can create a package global
log
variable:Then functions like
log.SetOutput()
are methods and modify your package global. This is awkward IMO if you have multiple packages in your program, because each of them has a different logger with different settings (but maybe that's good for some use cases). I also don't like this approach because it confusesgoimports
(which will want to insertlog
into your imports list).Or you can create your own wrapper (which is what I do). I have my own
log
package with its ownlogger
var:Then I make top-level functions to wrap Logrus:
This is slightly tedious, but allows me to add functions specific to my program:
So I can then do things like:
(I plan in the future to wrap
logrus.Entry
into my own type so that I can chain these better; currently I can't calllog.WithConn(c).WithRequest(r).Error(...)
because I can't addWithRequest()
tologrus.Entry
.)