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

Add TriggerLevelWriter #602

Merged
merged 1 commit into from
Nov 28, 2023
Merged

Add TriggerLevelWriter #602

merged 1 commit into from
Nov 28, 2023

Conversation

mitar
Copy link
Contributor

@mitar mitar commented Oct 15, 2023

Fixes #583.

@mitar
Copy link
Contributor Author

mitar commented Oct 17, 2023

In my own code, I then made:

func WithContext(ctx context.Context, writer io.Writer, level, conditionalLevel, triggerLevel zerolog.Level) (context.Context, func(), func()) {
	w := zerolog.NewTriggerLevelWriter(
		writer,
		conditionalLevel,
		triggerLevel,
	)
	ctxLogger := zerolog.New(w).Level(level).With().Timestamp().Logger()
	closeCtx := func() {
		_ = w.Close()
	}
	trigger := func() {
		_ = w.Trigger()
	}
	return ctxLogger.WithContext(ctx), closeCtx, trigger
}

One has then to call closeCtx after the context is not used anymore.

And I then have:

func NewHandler(writer io.Writer, level, conditionalLevel, triggerLevel zerolog.Level)) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			ctx, closeCtx, trigger := WithContext(req.Context(), writer, level, conditionalLevel, triggerLevel)
			defer closeCtx()
			panicking := true
			defer func() {
				if panicking {
					trigger()
				}
			}()
			req = req.WithContext(ctx)
			next.ServeHTTP(w, req)
			panicking = false
		})
	}
}

You can find them in my zerolog wrapper package.

writer.go Outdated Show resolved Hide resolved
writer.go Outdated Show resolved Hide resolved
writer.go Outdated Show resolved Hide resolved
writer.go Outdated Show resolved Hide resolved
@mitar
Copy link
Contributor Author

mitar commented Nov 21, 2023

@rs: I addressed your review comments.

writer.go Outdated Show resolved Hide resolved
@rs rs merged commit 93fb5cb into rs:master Nov 28, 2023
5 checks passed
madkins23 pushed a commit to madkins23/zerolog that referenced this pull request Mar 2, 2024
@mitar mitar deleted the TriggerLevelWriter branch May 13, 2024 22:26
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

Successfully merging this pull request may close these issues.

Support canonical log lines & log level per request
3 participants