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
mainfunction typically does this. The default value is LevelInfo.
Pretty straight forward, eh? Only want to log Info-and-above inproduction? Set the handler level to Info!
But what if you need to change to Debug level for a few minutes, without re-deploying the application? Enter the LevelVar! One of the more powerful features of the log/slog package that most people overlook.
Setting the [HandlerOptions.Level] field to a Level value fixes the handler’s minimum level throughout its lifetime. Setting it to a LevelVar allows the level to be varied dynamically. A LevelVar holds a Level and is safe to read or write from multiple goroutines. To vary the level dynamically for an entire program, first initialize a global LevelVar:
var programLevel = new(slog.LevelVar) // Info by defaultThen use the LevelVar to construct a handler, and make it the default:
h := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: programLevel}) slog.SetDefault(slog.New(h))Now the program can change its logging level with a single statement:
programLevel.Set(slog.LevelDebug)
With this, you could set up a /log_level endpoint, or any other mechanism in your application, that would dynamically change the log level, so you can do your debug-level observations, then later switch back to Info level.