Skip to content

Commit 8fbc737

Browse files
committed
fix: make Context(ctx) panic-free, add MustContext(ctx) for strict fallback (#75);
1 parent 9a4d015 commit 8fbc737

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,25 @@ logboek.Streams() // logboek.DefaultLogger().Streams()
7474
...
7575
```
7676

77+
### Using logboek with context.Context
78+
79+
Logboek can propagate a logger through `context.Context`:
80+
81+
```go
82+
ctx := logboek.NewContext(context.Background(), myLogger)
83+
84+
// Inside a helper function
85+
logboek.Context(ctx).LogLn("hello from helper")
86+
```
87+
88+
`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()`.
89+
90+
If you need the original strict behaviour (panic when no logger found), call `logboek.MustContext(ctx)` instead.
91+
92+
```go
93+
// Will panic if ctx has no logger
94+
l := logboek.MustContext(ctx)
95+
```
7796
<!---
7897
## Logging Methods
7998

main.go

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,10 +166,24 @@ func NewContext(ctx context.Context, logger types.LoggerInterface) context.Conte
166166
}
167167

168168
func Context(ctx context.Context) types.LoggerInterface {
169-
if ctx == context.Background() {
169+
if ctx == nil || ctx == context.Background() {
170170
return DefaultLogger()
171171
}
172172

173+
if ctxValue := ctx.Value(ctxLoggerKey); ctxValue != nil {
174+
if lgr, ok := ctxValue.(types.LoggerInterface); ok {
175+
return lgr
176+
}
177+
}
178+
179+
return DefaultLogger()
180+
}
181+
182+
func MustContext(ctx context.Context) types.LoggerInterface {
183+
if ctx == nil || ctx == context.Background() {
184+
panic("context is not bound with logboek logger")
185+
}
186+
173187
ctxValue := ctx.Value(ctxLoggerKey)
174188
if ctxValue == nil {
175189
panic("context is not bound with logboek logger")

0 commit comments

Comments
 (0)