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

[ctxzap] Add method to maybe extract logger from context #467

Closed
slnt opened this issue Oct 28, 2021 · 1 comment
Closed

[ctxzap] Add method to maybe extract logger from context #467

slnt opened this issue Oct 28, 2021 · 1 comment

Comments

@slnt
Copy link

slnt commented Oct 28, 2021

I am writing some database logging middleware that I would like tointeract with the request scoped logger. I don't expect that this middleware will always be used in a GRPC service context alongside grpc_zap and ctxzap, so I'd like for it to be able to fall back to some default logger when necessary.

There isn't a clear way to do this right now, since nullLogger is unexported.

To support this use case I'd like to propose adding one of:

func IsNullLogger(l *zap.Logger) bool {
	return l == nullLogger
}

or

// Extract takes the call-scoped Logger from grpc_zap middleware.
//
// It always returns a Logger that has all the grpc_ctxtags updated.
func Extract(ctx context.Context) *zap.Logger {
	l, ok := MaybeExtract(ctx)
	if !ok {
		return nullLogger
	}
	return l
}

// Extract takes the call-scoped Logger from grpc_zap middleware, if one exists, otherwise
// returns nil and false.
//
// It always returns a Logger that has all the grpc_ctxtags updated.
func MaybeExtract(ctx context.Context) (*zap.Logger, bool) {
	l, ok := ctx.Value(ctxMarkerKey).(*ctxLogger)
	if !ok || l == nil {
		return nil, false
	}

	// Add grpc_ctxtags tags metadata until now.
	fields := TagsToFields(ctx)
	// Add zap fields added until now.
	fields = append(fields, l.fields...)
	return l.logger.With(fields...), true
}
@bwplotka
Copy link
Collaborator

Great idea, but not sure why it has to be hosted in go-grpc-middlewares. The v2 version has logging.ExtractFields that should allow you to create your own context logger. Closing, unless you think that's not enough, we can reopen (:

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