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

Dynamic Hooks for zerolog #290

Closed
hooliganlin opened this issue Feb 8, 2021 · 1 comment
Closed

Dynamic Hooks for zerolog #290

hooliganlin opened this issue Feb 8, 2021 · 1 comment

Comments

@hooliganlin
Copy link

I'm trying to add span contexts via apmzerolog and to do that I'd have to add a hook. The weird thing I'm encountering is that if I started a span or some other context to be appended in my logs, I'd have to call the Hook method to append the context to the logger for every log event.

The main question is zerolog suppose to only add hooks on initialization of a Logger?

I created a wrapper over a zerolog.Logger and a method called TraceContext so that I can do something like:

logger.TraceContext(ctx).Info().Msg("successful message")

However, I have to attach a hook which creates a new value-based zerolog.Logger and then switch the semantics to return a pointer to a zerolog.Logger in order to chain it correctly with the other Events since the receiver for methods like Info() requires a *zerolog.Logger.

Example code:

// Logger wraps a zerolog.Logger as an adapter.
type Logger struct {
	underlying zerolog.Logger
}

func NewLogger(logger zerolog.Logger) *Logger {
	return &Logger{
		underlying: logger,
	}
}

// TraceContext attaches a context.Context to the underlying zerolog.Logger and attaches an apm trace hook.
func (l *Logger) TraceContext(ctx context.Context) *zerolog.Logger {
	// TODO The switching of pointer and value semantic might go against what zerolog was trying to convey,
	// but we need figure out if hooks are meant to be only initialized once vs being added dynamically
	logger := l.underlying.Hook(apmzerolog.TraceContextHook(ctx))
	return &logger
}
@danielbprice
Copy link
Contributor

I believe that this is probably resolved now that #559 has been merged. I am using it for Datadog.

@rs rs closed this as completed Jul 25, 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

3 participants