Debian Codegraph @

exp/zapslog/options.go

raw
1 // Copyright (c) 2023 Uber Technologies, Inc.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a copy
4 // of this software and associated documentation files (the "Software"), to deal
5 // in the Software without restriction, including without limitation the rights
6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 // copies of the Software, and to permit persons to whom the Software is
8 // furnished to do so, subject to the following conditions:
9 //
10 // The above copyright notice and this permission notice shall be included in
11 // all copies or substantial portions of the Software.
12 //
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 // THE SOFTWARE.
20
21 //go:build go1.21
22
23 package zapslog
24
25 import "log/slog"
26
27 // A HandlerOption configures a slog Handler.
28 type HandlerOption interface {
29 apply(*Handler)
30 }
31
32 // handlerOptionFunc wraps a func so it satisfies the Option interface.
33 type handlerOptionFunc func(*Handler)
34
35 func (f handlerOptionFunc) apply(handler *Handler) {
36 f(handler)
37 }
38
39 // WithName configures the Logger to annotate each message with the logger name.
40 func WithName(name string) HandlerOption {
41 return handlerOptionFunc(func(h *Handler) {
42 h.name = name
43 })
44 }
45
46 // WithCaller configures the Logger to include the filename and line number
47 // of the caller in log messages--if available.
48 func WithCaller(enabled bool) HandlerOption {
49 return handlerOptionFunc(func(handler *Handler) {
50 handler.addCaller = enabled
51 })
52 }
53
54 // WithCallerSkip increases the number of callers skipped by caller annotation
55 // (as enabled by the [WithCaller] option).
56 //
57 // When building wrappers around the Logger,
58 // supplying this Option prevents Zap from always reporting
59 // the wrapper code as the caller.
60 func WithCallerSkip(skip int) HandlerOption {
61 return handlerOptionFunc(func(log *Handler) {
62 log.callerSkip += skip
63 })
64 }
65
66 // AddStacktraceAt configures the Logger to record a stack trace
67 // for all messages at or above a given level.
68 func AddStacktraceAt(lvl slog.Level) HandlerOption {
69 return handlerOptionFunc(func(log *Handler) {
70 log.addStackAt = lvl
71 })
72 }