-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
67 lines (54 loc) · 1.81 KB
/
Copy pathcontext.go
File metadata and controls
67 lines (54 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// SPDX-FileCopyrightText: 2026 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
package sallust
import (
"context"
"go.uber.org/zap"
)
// contextKey is the internal key type used to access a zap.Logger
// within a context.Context instance
type contextKey struct{}
// defaultLogger is used when no logger exists in the context
var defaultLogger *zap.Logger = zap.NewNop()
// Default returns the default zap.Logger used when no logger is
// found in a context.
func Default() *zap.Logger {
return defaultLogger
}
// With places a zap.Logger into the context. If the given logger is nil,
// this function returns the parent as-is. Since the Get functions return
// a nop logger when there is no logger in the context, a nil logger
// can be safely ignored.
//
// See: https://pkg.go.dev/go.uber.org/zap?tab=doc#Logger
func With(parent context.Context, logger *zap.Logger) context.Context {
if logger != nil {
return context.WithValue(parent, contextKey{}, logger)
}
return parent
}
// Get returns the zap.Logger from the given context. If no zap.Logger
// exists, this function returns Default().
//
// See: https://pkg.go.dev/go.uber.org/zap?tab=doc#Logger
// See: https://pkg.go.dev/go.uber.org/zap?tab=doc#NewNop
func Get(ctx context.Context) *zap.Logger {
if l, ok := ctx.Value(contextKey{}).(*zap.Logger); ok {
return l
}
return Default()
}
// GetDefault attempts to find a zap.Logger in the given context. If none is
// found, the given default is returned. If the given default is nil, then
// Default() is returned instead.
//
// See: https://pkg.go.dev/go.uber.org/zap?tab=doc#Logger
func GetDefault(ctx context.Context, def *zap.Logger) *zap.Logger {
if l, ok := ctx.Value(contextKey{}).(*zap.Logger); ok {
return l
}
if def != nil {
return def
}
return Default()
}