Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,25 @@ logboek.Streams() // logboek.DefaultLogger().Streams()
...
```

### Using logboek with context.Context

Logboek can propagate a logger through `context.Context`:

```go
ctx := logboek.NewContext(context.Background(), myLogger)

// Inside a helper function
logboek.Context(ctx).LogLn("hello from helper")
```

`logboek.Context(ctx)` is **safe**: if the provided context does not hold a logger (or is `nil`/`context.Background()`), it automatically falls back to `logboek.DefaultLogger()`.

If you need the original strict behaviour (panic when no logger found), call `logboek.MustContext(ctx)` instead.

```go
// Will panic if ctx has no logger
l := logboek.MustContext(ctx)
```
<!---
## Logging Methods

Expand Down
16 changes: 15 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,24 @@ func NewContext(ctx context.Context, logger types.LoggerInterface) context.Conte
}

func Context(ctx context.Context) types.LoggerInterface {
if ctx == context.Background() {
if ctx == nil || ctx == context.Background() {
return DefaultLogger()
}

if ctxValue := ctx.Value(ctxLoggerKey); ctxValue != nil {
if lgr, ok := ctxValue.(types.LoggerInterface); ok {
return lgr
}
}

return DefaultLogger()
}

func MustContext(ctx context.Context) types.LoggerInterface {
if ctx == nil || ctx == context.Background() {
panic("context is not bound with logboek logger")
}

ctxValue := ctx.Value(ctxLoggerKey)
if ctxValue == nil {
panic("context is not bound with logboek logger")
Expand Down