slog-multi
slog-multi copied to clipboard
Fanout silently stops working
Hi! I was trying to make a logger that prints to both a file and stdOut, but I experienced a problem where I couldn't log anything after wrapping the logger in a convenience function:
func CreateLogger() *slog.Logger {
f, err := os.OpenFile("logfile.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening logfile: %v", err)
}
defer f.Close()
stdOut := os.Stderr
handlerOpts := &slog.HandlerOptions{
AddSource: true,
Level: slog.LevelInfo,
}
stdOutHandler := slog.NewTextHandler(stdOut, handlerOpts)
fileHandler := slog.NewJSONHandler(f, handlerOpts)
newSlog := slog.New(
slogmulti.Fanout(
fileHandler,
stdOutHandler,
),
)
return newSlog
}
After getting some help, I realised I'd made a noob mistake and closed the file handler when the function exited.
All of this ran fine, but when trying to use the logger, I didn't get any output. Not even in stdOut or stdErr.
I'm unsure if this is an actual issue, but I had problems debugging why I didn't get any output, so the codebase could perhaps be improved. I'm thinking of some documentation describing why this could happen or even better, have the code detect this and give some output saying that X handler has stopped working.
A handler can return an error, but the slog logger does not use it.