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


Log levels

I'm launching a new live course: **Idiomatic Testing in Go**. The course begins May 5. Early-bird pricing is in effect until April 28. Why Go avoids assert libraries Better alternatives to mocks Make writing tests fun! See pricing & reserve → log/slog provides some rather sophisticated capabilities around log levels. We’ll get into it, but the good news is, you don’t need to care about how sophisticated it can get, if you don’t care.


Logging common fields

It’s common that you’ll want to include certain attributes in all logs in an application or component. log/slog makes this pretty easy. Overview … Some attributes are common to many log calls. For example, you may wish to include the URL or trace identifier of a server request with all log events arising from the request. Rather than repeat the attribute with every log call, you can use Logger.With to construct a new Logger containing the attributes:


Handler configuration

The default slog handlers are quite configurable. Overview … Both TextHandler and JSONHandler can be configured with HandlerOptions. There are options for setting the minimum level (see Levels, below), displaying the source file and line of the log call, and modifying attributes before they are logged. While HandlerOptions only exposes three fields: AddSource bool Level Leveler ReplaceAttr func(groups []string, a Attr) Attr The last one provides an immense amount of flexibility, letting you filter, replace, or augment log key/value pairs as they are processed.

Get daily content like this in your inbox!

Subscribe