Reputation: 752
I am implementing logger in Go. I am thinking of using logrus for this. I wanted to understand limitations of the built in log package.
I know that if we want to write logs to file or implement rolling file logs etc we would need to add this feature manually. Is there any other limitations for which we have to choose an external log package?
Upvotes: 4
Views: 3104
Reputation: 2882
Logging to file can be done multiple ways.
The 12-factor-app way (not just the 12 factor app way, but 12 factor apps make a point of doing it this way) of doing it would be to log to STDOUT and/or STDERR and then piping it elsewhere for deployment. This also makes development easy. Also if you're using something like containers to deploy your program, they log the container's STDOUT and STDERR to a file to begin with.
The std lib log
package has two ways to change output to a file.
One way is as follows:
log.SetOutput(<something that implements io.Writer, probably os.File>)
log.Println("some message")
The other is:
logger := log.New(<something that implements io.Writer, probably os.File>, <a prefix String>, <some flag, see https://golang.org/pkg/log/#pkg-constants>)
logger.Println("some message")
The second option is also how you can implement different log levels (i.e. INFO, DEBUG, WARN, ERROR, etc) by having each level be its own logger.
However logrus gives you a lot of this already for you, so that is probably your best bet if you just want to have logging implemented quickly.
Upvotes: 2
Reputation: 417412
Logging to file using the builtin log
package is not an issue, you can use log.SetOutput()
or Logger.SetOutput()
to set a destination io.Writer
other than the default os.Stderr
, for example a file *os.File
.
What's missing and often whished for is leveled logging (e.g. INFO
, WARN
, DEBUG
, ERROR
etc.). For a reasoning, read blog post Dave Cheney: Let's talk about logging.
You also can't enforce a specific log.Logger
to be used by designated packages unless those packages "willing" to cooperate (e.g. they provide a SetLogger()
function).
Rolling log files is also a missing feature.
On the other hand, it's also very easy to "extend" the standard logger to log into MongoDB for example, for details see Go: Create io.Writer inteface for logging to mongodb database. Using MongoDB you can also use a Capped collection which will implicitly give you a "rolling file" functionality.
Upvotes: 1