Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fanout silently stops working #6

Open
MathiasKandelborg opened this issue Mar 26, 2024 · 1 comment
Open

Fanout silently stops working #6

MathiasKandelborg opened this issue Mar 26, 2024 · 1 comment

Comments

@MathiasKandelborg
Copy link

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.

@samber
Copy link
Owner

samber commented Mar 26, 2024

A handler can return an error, but the slog logger does not use it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants