Overriding the default handler

April 8, 2026

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

Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


The global logger

I’m going to do something I haven’t done before in these stdlib tours, and that is skip over a huge section of the GoDoc. That’s becase a huge section here is entirely redundant with what comes later: func Debug func Debug(msg string, args ...any) Debug calls Logger.Debug on the default logger. And we have virtually identical entries for each of the following: DebugContext Error ErrorContext Info InfoContext Log LogAttrs Warn WarnContext Each of these is simply an alias to the identically named method on the default logger.


slog Handler methods

slog.Handler is an interface type. We’re going to look at each method on that interface in turn. Understanding these methods is valuable if you’re ever implementing your own handler. If you’re only using slog to produce logs using existing handlers, you could skip this part… though maybe you’ll learn something interesting anyway! type Handler type Handler interface { // Enabled reports whether the handler handles records at the given level. // The handler ignores records whose level is lower.


Attribute equality

func (Attr) Equal func (a Attr) Equal(b Attr) bool Equal reports whether a and b have equal keys and values. That’s a pretty obvious, and opaque statement. How is equality determined? We have to look at the source to determine: func (a Attr) Equal(b Attr) bool { return a.Key == b.Key && a.Value.Equal(b.Value) } Okay, so it returns true if the keys are equal (that’s simple—they’re just strings) AND if the values are equal.

Get daily content like this in your inbox!

Subscribe