From a712f6193674c928bb853f2cb40e0ed68ebb5ef7 Mon Sep 17 00:00:00 2001 From: Kirill Date: Fri, 21 Apr 2023 13:55:19 +0400 Subject: [PATCH] doc(readme): explain zerolog with context (#544) Add section about `context.Context` usage with zerolog instance --- README.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e8cbfc2..d424a72 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Find out [who uses zerolog](https://github.com/rs/zerolog/wiki/Who-uses-zerolog) * [Sampling](#log-sampling) * [Hooks](#hooks) * [Contextual fields](#contextual-logging) -* `context.Context` integration +* [`context.Context` integration](#contextcontext-integration) * [Integration with `net/http`](#integration-with-nethttp) * [JSON and CBOR encoding formats](#binary-encoding) * [Pretty logging for development](#pretty-logging) @@ -511,6 +511,30 @@ stdlog.Print("hello world") // Output: {"foo":"bar","message":"hello world"} ``` +### context.Context integration + +The `Logger` isntance could be attached to `context.Context` values with `logger.WithContext(ctx)` +and extracted from it using `zerolog.Ctx(ctx)`. + +Example to add logger to context: +```go +// this code attach logger instance to context fields +ctx := context.Background() +logger := zerolog.New(os.Stdout) +ctx = logger.WithContext(ctx) +someFunc(ctx) +``` + +Extracting logger from context: +```go +func someFunc(ctx context.Context) { + // get logger from context. if it's nill, then `zerolog.DefaultContextLogger` is returned, + // if `DefaultContextLogger` is nil, then disabled logger returned. + logger := zerolog.Ctx(ctx) + logger.Info().Msg("Hello") +} +``` + ### Integration with `net/http` The `github.com/rs/zerolog/hlog` package provides some helpers to integrate zerolog with `http.Handler`.