Skip to content

Instantly share code, notes, and snippets.

@palkan

palkan/main.go Secret

Created June 21, 2024 21:18
Show Gist options
  • Save palkan/c735f7bb85b9950189ff56da9d9cd520 to your computer and use it in GitHub Desktop.
Save palkan/c735f7bb85b9950189ff56da9d9cd520 to your computer and use it in GitHub Desktop.
Go slog level switch demo
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)
}
@mrngm
Copy link

mrngm commented Jul 4, 2024

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).

@lechuhuuha
Copy link

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).

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