-
-
Save palkan/c735f7bb85b9950189ff56da9d9cd520 to your computer and use it in GitHub Desktop.
Go slog level switch demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log/slog" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
) | |
var LOG_LEVEL = new(slog.LevelVar) | |
func main() { | |
LOG_LEVEL.Set(slog.LevelInfo) | |
opts := &slog.HandlerOptions{ | |
Level: LOG_LEVEL, | |
} | |
logger := slog.New( | |
slog.NewTextHandler(os.Stdout, opts), | |
) | |
// trap SIGQUIT to toggle debug level | |
// run in your terminal: | |
// kill -3 <pid> | |
sigChan := make(chan os.Signal, 1) | |
signal.Notify(sigChan, syscall.SIGQUIT) | |
go func() { | |
for { | |
<-sigChan | |
currentLevel := LOG_LEVEL.Level() | |
if currentLevel != slog.LevelDebug { | |
SetLogLevel(slog.LevelDebug) | |
} else { | |
SetLogLevel(slog.LevelInfo) | |
} | |
logger.Info("Log level changed") | |
} | |
}() | |
counter := 0 | |
logger = logger.With("pid", os.Getpid()) | |
for { | |
logger.Debug("ready to increase counter in 1s") | |
time.Sleep(time.Second) | |
counter++ | |
logger.Info("counter increased", "counter", counter) | |
logger.Debug("cooldown for 1s") | |
time.Sleep(time.Second) | |
} | |
} | |
func SetLogLevel(lvl slog.Level) { | |
LOG_LEVEL.Set(lvl) | |
} |
Do note the default interpretation of SIGQUIT in Go that you're currently overriding:
The SIGQUIT signal is sent when the user at the controlling terminal presses the quit character, which by default is ^\ (Control-Backslash). In general you can cause a program to simply exit by pressing ^C, and you can cause it to exit with a stack dump by pressing ^\ .
Perhaps a better signal for runtime changing of log levels could be
SIGUSR1
orSIGUSR2
(although I've seen many examples ofSIGHUP
being used for hot-reloading configuration as well).
yes i understand
its a trade-off after all
but still a good idea handle hot reload
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do note the default interpretation of SIGQUIT in Go that you're currently overriding:
Perhaps a better signal for runtime changing of log levels could be
SIGUSR1
orSIGUSR2
(although I've seen many examples ofSIGHUP
being used for hot-reloading configuration as well).