Handler configuration

April 14, 2026

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. This lets you do things like filter out sensitive or noisy log information, or add additional details to errors, etc.

That said, the option you’re most likely to use the most is the simpler Level field. This lets you set the level for the handler—only want ERROR or higher logs to go to a particular place? This is where you control that.

And AddSource instructs the handler to compute the source code position of the log statement and add a SourceKey attribute to the output.


Share this

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

Unsure? Browse the archive .

Related Content


Chosing an slog handler

log/slog ships with two default handlers: the TextHandler and the JSONHandler. Overview … For more control over the output format, create a logger with a different handler. This statement uses New to create a new logger with a TextHandler that writes structured records in text form to standard error: logger := slog.New(slog.NewTextHandler(os.Stderr, nil)) TextHandler output is a sequence of key=value pairs, easily and unambiguously parsed by machine. This statement: logger.Info("hello", "count", 3) produces this output:


Filtering logs by level

Levels In an application, you may wish to log messages only at a certain level or greater. One common configuration is to log messages at Info or higher levels, suppressing debug logging until it is needed. The built-in handlers can be configured with the minimum level to output by setting [HandlerOptions.Level]. The program’s main function typically does this. The default value is LevelInfo. Pretty straight forward, eh? Only want to log Info-and-above inproduction?


Values

TIL Logger.LogAttrs is a thing! But what is that thing?? Yesterday I mentioned that using an slog.Attr can be marginally more efficient than using naked key/value pairs in a log call. While true, that glosses over what is likely to be a much more impactful performance consideration in certain applications… Attrs and Values … The value part of an Attr is a type called Value. Like an [any], a Value can hold any Go value, but it can represent typical values, including all numbers and strings, without an allocation.

Get daily content like this in your inbox!

Subscribe