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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
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 ---`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.