Today I’m going to jump around a bit in the GoDoc, to talk about a topic I mentioned last time: how to override the default logger.
Overview
…
Setting a logger as the default with
slog.SetDefault(logger)will cause the top-level functions like Info to use it. SetDefault also updates the default logger used by the log package, so that existing applications that use log.Printf and related functions will send log records to the logger’s handler without needing to be rewritten.
While I generally discourage use of the default logger, for reasons I’ll get into another day, if you have an application that uses either the default log handler or the default log/slog handler, you can at least control how it works!
file, err := os.Open("/var/log/myapp.log")
if err != nil {
panic(err)
}
logger := slog.New(slog.NewJSONHandler(file, nil))
slog.SetDefault(logger)
// Some time later...
slog.Info("Interesting things are afoot!") // Written to /var/log/myapp.log
// Meanwhile, back at the farm...
log.Printf("And then he turned to me and said...") // Also written to /var/log/myapp.log