-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.go
More file actions
274 lines (256 loc) · 8.96 KB
/
Copy pathlogger.go
File metadata and controls
274 lines (256 loc) · 8.96 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// Package log provides a structured logging system built on top of Zap.
//
// This file contains the configuration and initialization functionality for the logging system.
// It uses the functional options pattern to provide a flexible and extensible way to configure
// the underlying Zap logger with sensible defaults.
//
// The main components in this file are:
//
// 1. The NewLogger function for creating and configuring a new logger instance
// 2. A set of With* functions that return Option values for different configuration aspects
// 3. The Option type, which is a function that modifies the internal options struct
//
// Example usage:
//
// // Create a new logger with custom configuration
// logger := log.NewLogger(
// log.WithLevel(zapcore.InfoLevel),
// log.WithFields(zap.String("service", "api")),
// log.AsGlobal(), // Set as the global logger
// )
//
// // Use the logger directly
// logger.Info("Server starting")
//
// // Or use the global functions after setting it as global
// log.Info("Using global logger")
package log
import (
"log"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// options is an internal struct that holds the configuration options for the logger.
// It is modified by Option functions and used by NewLogger to configure the zap.Logger.
type options struct {
level zapcore.Level // The minimum log level to output
sampling *zap.SamplingConfig // Configuration for log sampling
makeGlobal bool // Whether to set the created logger as the global logger
fields []zap.Field // Fields to include in all log entries
cfg *zap.Config // Custom zap configuration (overrides other options if provided)
redirectStdLog *zapcore.Level // Level at which to redirect standard library logs
core zapcore.Core
}
// Option defines a functional option for configuring logger behavior.
//
// This type implements the functional options pattern, which provides a flexible
// and extensible way to configure the logger. Each Option is a function that
// modifies the internal options struct during initialization.
//
// Options can be composed and passed to NewLogger to customize the logger's behavior.
// This approach allows for adding new configuration options in the future without
// breaking existing code.
type Option func(*options)
// WithLevel sets the minimum logging level for the logger.
//
// The level determines which log entries will be output. Any entries with a level
// lower than the specified level will be discarded. The default level is InfoLevel
// when using the production configuration.
//
// Available levels (in ascending order of severity):
// - DebugLevel: Detailed information for debugging
// - InfoLevel: General operational information
// - WarnLevel: Warning conditions
// - ErrorLevel: Error conditions
// - DPanicLevel: Critical errors in development mode
// - PanicLevel: Critical errors that cause panic
// - FatalLevel: Critical errors that terminate the program
//
// Example:
//
// logger := log.NewLogger(log.WithLevel(zapcore.DebugLevel))
func WithLevel(level zapcore.Level) Option {
return func(o *options) {
o.level = level
}
}
// WithSampling sets a custom sampling configuration for the logger.
//
// Sampling can be used to reduce the volume of logs by only recording a fraction
// of repeated log entries within a given time period. This is useful for high-volume
// logs that might otherwise overwhelm the logging system.
//
// The sampling configuration specifies:
// - Initial: Number of entries to log before sampling begins
// - Thereafter: Sample rate after Initial entries (1 in N entries will be logged)
// - Tick: Time period for the sampling window
//
// Example:
//
// // Log first 100 entries, then only 1 in 100 for each 1-second window
// sampling := &zap.SamplingConfig{
// Initial: 100,
// Thereafter: 100,
// Tick: time.Second,
// }
// logger := log.NewLogger(log.WithSampling(sampling))
func WithSampling(sampling *zap.SamplingConfig) Option {
return func(o *options) {
o.sampling = sampling
}
}
// AsGlobal sets the created logger as the global logger instance.
//
// When this option is used, the logger created by NewLogger will replace the
// global zap logger (accessible via zap.L()) and the global SugaredLogger
// (accessible via zap.S()). This affects all code that uses these global loggers,
// including the global logging functions in this package.
//
// Example:
//
// // Create a new logger and set it as the global logger
// log.NewLogger(log.AsGlobal())
//
// // Now global functions will use this logger
// log.Info("This uses the new global logger")
func AsGlobal() Option {
return func(o *options) {
o.makeGlobal = true
}
}
// WithFields adds fields to be included in all log entries created by the logger.
//
// These fields are useful for adding context that is relevant to all logs from
// a particular component or service, such as service name, version, or environment.
//
// Example:
//
// logger := log.NewLogger(
// log.WithFields(
// zap.String("service", "api"),
// zap.String("version", "1.0.0"),
// zap.String("env", "production"),
// ),
// )
//
// // All logs from this logger will include the specified fields
// logger.Info("Server starting") // Includes service, version, and env fields
func WithFields(fields ...zap.Field) Option {
return func(o *options) {
o.fields = fields
}
}
// WithConfig sets a custom zap.Config for the logger.
//
// This option provides complete control over the logger configuration, overriding
// any other options that affect the configuration. It's useful when you need
// advanced customization beyond what the other options provide.
//
// If this option is not provided, NewLogger uses zap.NewProductionConfig() as
// the default configuration.
//
// Example:
//
// // Create a custom configuration
// cfg := zap.NewDevelopmentConfig()
// cfg.Encoding = "json"
// cfg.OutputPaths = []string{"stdout", "/var/log/app.log"}
//
// // Create a logger with the custom configuration
// logger := log.NewLogger(log.WithConfig(&cfg))
func WithConfig(cfg *zap.Config) Option {
return func(o *options) {
o.cfg = cfg
}
}
// WithRedirectStdLog redirects the standard library's log package output to the zap logger.
//
// This option captures logs written using the standard library's log package and
// redirects them to the zap logger at the specified level. This is useful for
// capturing logs from third-party libraries that use the standard library logger.
//
// Example:
//
// // Redirect standard library logs to the zap logger at info level
// logger := log.NewLogger(log.WithRedirectStdLog(zapcore.InfoLevel))
//
// // Now standard library logs will be captured by zap
// stdlog.Println("This will be captured by zap")
func WithRedirectStdLog(lvl zapcore.Level) Option {
return func(o *options) {
o.redirectStdLog = &lvl
}
}
func WithCore(core zapcore.Core) Option {
return func(o *options) {
o.core = core
}
}
// NewLogger creates a new zap.Logger instance configured using the provided options.
//
// This function is the main entry point for creating a logger in this package.
// It applies the provided options to configure the logger and returns a new zap.Logger
// instance ready for use.
//
// By default, if no WithConfig option is provided, the logger will use zap's production
// configuration (JSON format, info level, timestamps, caller information). This can be
// overridden by providing a custom configuration with WithConfig.
//
// If an error occurs during logger creation, the function will log a fatal error and
// terminate the program. This is a design choice to ensure that logging is always
// properly initialized before the application continues.
//
// Parameters:
// - opts: A variadic list of Option functions to configure the logger
//
// Returns:
// - A configured *zap.Logger instance
//
// Example:
//
// // Create a basic logger
// logger := log.NewLogger()
//
// // Create a logger with custom options
// logger := log.NewLogger(
// log.WithLevel(zapcore.DebugLevel),
// log.WithFields(zap.String("app", "myapp")),
// log.AsGlobal(),
// )
//
// // Use the logger
// logger.Info("Application started", zap.Int("port", 8080))
func NewLogger(opts ...Option) *zap.Logger {
var opt options
for _, o := range opts {
o(&opt)
}
var logger *zap.Logger
var err error
if opt.core != nil {
// Use the provided custom core
logger = zap.New(opt.core, zap.Fields(opt.fields...), zap.AddCallerSkip(1))
} else {
// Build logger from config
var cfg zap.Config
if opt.cfg != nil {
cfg = *opt.cfg
} else {
cfg = zap.NewProductionConfig()
}
logger, err = cfg.Build(zap.Fields(opt.fields...), zap.AddCallerSkip(1))
if err != nil {
log.Fatalf("failed to initialize logger: %v", err)
}
}
if opt.redirectStdLog != nil {
_, err = zap.RedirectStdLogAt(logger, *opt.redirectStdLog)
if err != nil {
log.Fatalf("failed to redirect std log: %v", err)
}
}
if opt.makeGlobal {
zap.ReplaceGlobals(logger)
}
return logger
}