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

Slog with AddSource: true is not working correctly due to wrapper in watermill #404

Open
ganeshdipdumbare opened this issue Oct 24, 2023 · 0 comments

Comments

@ganeshdipdumbare
Copy link

ganeshdipdumbare commented Oct 24, 2023

Description
The slog logger is having an option to turn on source with AddSource: true handler option. This will show the caller with line no in the log.
Due to wrapper around slog in the watermill, it always shows the following line for debug and same for other log levels -

"source":{"function":"github.com/ThreeDotsLabs/watermill.(*SlogLoggerAdapter).Info","file":"/go/pkg/mod/github.com/!three!dots!labs/watermill@v1.3.5/slog.go","line":33

As per my finding the issue is slog is getting the caller at the following line no -
https://cs.opensource.google/go/go/+/refs/tags/go1.21.3:src/log/slog/logger.go;l=217

I have done quick fix while creating slog logger handler by adding following code

handlerOption := &slog.HandlerOptions{
		Level:     slogLevel,
		AddSource: true,
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == "source" && isForWatermill {
				const callerDepth = 8
				pc := make([]uintptr, 1)
				runtime.Callers(callerDepth, pc)
				fs := runtime.CallersFrames([]uintptr{pc[0]})
				f, _ := fs.Next()
				return slog.Attr{
					Key:   "@caller",
					Value: slog.StringValue(fmt.Sprintf("function:%s %s:%d", f.Function, f.File, f.Line)),
				}
			}
			return a
		},
	}
@ganeshdipdumbare ganeshdipdumbare changed the title Slog with AddSource: true is not working correctly due to wrapper in watermill Slog with AddSource: true is not working correctly due to wrapper in watermill Oct 24, 2023
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

1 participant