Change Log Level At Runtime With LevelVar

Give the slog handler a LevelVar as its threshold so the minimum level can be raised or lowered while the process runs, with no logger rebuild.

GoConfig Management

Code

gosnippet
32 lines
package main

import (
	"bytes"
	"fmt"
	"log/slog"
)

func main() {
	var level slog.LevelVar // 零值即 Info
	var out bytes.Buffer
	logger := slog.New(slog.NewTextHandler(&out, &slog.HandlerOptions{Level: &level}))

	logger.Debug("debug detail dropped") // 低于阈值,被过滤
	logger.Info("service started")
	fmt.Println("--- lowering threshold to Debug ---")

	// 运行期调低阈值:handler 持有的是指针,改动立刻生效
	level.Set(slog.LevelDebug)
	logger.Debug("debug detail kept", "goroutines", 4)
	logger.Warn("queue depth high", "depth", 12)

	fmt.Println("level now:", level.Level())
	fmt.Println(out.String())

	// 调高到 Error 后,Warn 也不再写出
	level.Set(slog.LevelError)
	logger.Warn("warn filtered again")
	logger.Error("disk full", "path", "/var/data")
	fmt.Println("--- after raising to Error ---")
	fmt.Println(out.String())
}

How the snippet works

Under the hood: the function main.

Points of care

  • Built-in APIs only, so there is no supply chain to vet.

Using it

The --- lowering threshold to Debug --- banner opens the mid-run change: the buffer dump after level now: Debug now contains debug detail kept, and the final --- after raising to Error --- dump shows the process log with no line from warn filtered again, which the raised threshold refused to write.

Key statements

logger := slog.New(slog.NewTextHandler(&out, &slog.HandlerOptions{Level: &level}))

Interactive Tools for This Topic

FAQ

What does Change Log Level At Runtime With LevelVar print when run?
Execute the whole file; each printed line is prefixed with a label like `--- lowering threshold to Debug ---`, `level now:`, `--- after raising to Error ---`.