httplog icon indicating copy to clipboard operation
httplog copied to clipboard

Add custom value from context to log

Open marko995 opened this issue 1 year ago • 0 comments

Hi guys, is it possible to add a custom value from context to log, for example userID? The idea is to create custom middleware that will take userID from jwt, and put it in context. So, I want logger to print userID whenever I log something.

I found workaround, but I don't like it:

func CustomLogger(ctx context.Context) *slog.Logger {
	logger := httplog.LogEntry(ctx)

	userId := ctx.Value("userID")
	if userId != nil {
		return logger.With("userID", userId)
	}
	return logger
}

Is there any better way to do this, like modifying opts? When I used slog, I used this approach: https://stackoverflow.com/a/77314908

marko995 avatar May 26 '24 00:05 marko995