-
-
Save palkan/c735f7bb85b9950189ff56da9d9cd520 to your computer and use it in GitHub Desktop.
| 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 or SIGUSR2 (although I've seen many examples of SIGHUP being used for hot-reloading configuration as well).
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
SIGUSR1orSIGUSR2(although I've seen many examples ofSIGHUPbeing used for hot-reloading configuration as well).
yes i understand
its a trade-off after all
but still a good idea handle hot reload
never knew signal could be use with something like this
Thanks for the infomation <3