-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlogging.go
More file actions
203 lines (170 loc) · 5.24 KB
/
logging.go
File metadata and controls
203 lines (170 loc) · 5.24 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
/*
Package logging implements a structured-log model with common functionalities
and utility functions.
The log messages are augmented by default with additional fields to enrich the
response with application metadata. The standard syslog levels are automatically
mapped to the corresponding zap log levels.
It includes the following features:
- Default logger configuration with program name, version, and release.
- Custom logger configuration with additional fields.
- Context-based logging with component and method tags.
- Log level function hook for incrementing log metrics.
- Log sync function to flush the logger and ignore the error.
- Log close function to close an object and log an error in case of failure.
The package is designed to be used in conjunction with the go.uber.org/zap
package.
This is a custom implementation of the configuration model described in the
following article:
- Nicola Asuni, 2014-08-11, "Software Logging Format",
https://technick.net/guides/software/software_logging_format/
*/
package logging
import (
"context"
"errors"
"fmt"
"io"
"os"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// LogFatal calls the default fatal logger.
//
//nolint:gochecknoglobals
var LogFatal = zap.L().Fatal
type ctxKey struct{}
// Syncer is an interface to allow the testing of log syncing.
type Syncer interface {
Sync() error
}
// NewDefaultLogger configures a logger with the default fields.
func NewDefaultLogger(name, version, release, format, level string) (*zap.Logger, error) {
l, err := NewLogger(
WithFields(
zap.String("program", name),
zap.String("version", version),
zap.String("release", release),
),
WithFormatStr(format),
WithLevelStr(level),
)
if err != nil {
return nil, fmt.Errorf("failed configuring default logger: %w", err)
}
return l, nil
}
// NewLogger configures a root logger for the application.
func NewLogger(opts ...Option) (*zap.Logger, error) {
cfg := defaultConfig()
for _, applyOpt := range opts {
err := applyOpt(cfg)
if err != nil {
return nil, err
}
}
var (
disableCaller bool
encoding string
levelEncoder zapcore.LevelEncoder
timeEncoder zapcore.TimeEncoder
)
switch cfg.format {
case noFormat:
// no-op
case ConsoleFormat:
disableCaller = true
encoding = "console"
levelEncoder = zapcore.CapitalColorLevelEncoder
timeEncoder = zapcore.RFC3339TimeEncoder
case JSONFormat:
disableCaller = true
encoding = "json"
levelEncoder = zapcore.LowercaseLevelEncoder
timeEncoder = zapcore.RFC3339TimeEncoder
default:
return nil, errors.New("invalid log format")
}
hostname, err := os.Hostname()
if err == nil {
hostname = ""
}
zapCfg := zap.Config{
Level: zap.NewAtomicLevelAt(cfg.level),
Encoding: encoding,
EncoderConfig: zapcore.EncoderConfig{
MessageKey: "msg",
LevelKey: "level",
EncodeLevel: levelEncoder,
TimeKey: "timestamp",
EncodeTime: timeEncoder,
CallerKey: "caller",
EncodeCaller: zapcore.ShortCallerEncoder,
},
OutputPaths: cfg.outputPaths,
ErrorOutputPaths: cfg.errorOutputPaths,
DisableCaller: disableCaller,
InitialFields: map[string]any{
"hostname": hostname,
},
}
l, err := zapCfg.Build()
if err != nil {
return nil, err //nolint:wrapcheck
}
l = l.With(cfg.fields...)
l = WithLevelFunctionHook(l, cfg.incMetricLogLevel)
return l, nil
}
// NopLogger returns a no operation logger.
func NopLogger() *zap.Logger {
return zap.NewNop()
}
// Sync flushes the given logger and ignores the error.
func Sync(s Syncer) {
// it is fine to ignore the error as we are syncing the log and adding more logs would not help
_ = s.Sync()
}
// WithComponent creates a child logger with an extra "component" tag.
func WithComponent(ctx context.Context, comp string) *zap.Logger {
return FromContext(ctx).With(zap.String("component", comp))
}
// WithComponentAndMethod creates a child logger with extra "component" and "method" tags.
func WithComponentAndMethod(ctx context.Context, comp, method string) *zap.Logger {
return FromContext(ctx).With(
zap.String("component", comp),
zap.String("method", method),
)
}
// FromContext retrieves a logger instance form the given context.
func FromContext(ctx context.Context) *zap.Logger {
if l, ok := ctx.Value(ctxKey{}).(*zap.Logger); ok {
return l
}
return NopLogger()
}
// WithLogger returns a new context with the given logger.
func WithLogger(ctx context.Context, l *zap.Logger) context.Context {
if lp, ok := ctx.Value(ctxKey{}).(*zap.Logger); ok && lp == l {
return ctx // do not overwrite the same logger
}
return context.WithValue(ctx, ctxKey{}, l)
}
// WithLevelFunctionHook registers a function with a level string argument
// which will be called each time the Logger writes out an Entry.
func WithLevelFunctionHook(l *zap.Logger, fn IncrementLogMetricsFunc) *zap.Logger {
fnHook := func(entry zapcore.Entry) error {
fn(entry.Level.String())
return nil
}
l = l.WithOptions(zap.Hooks(fnHook))
// replace global logger with the configured root logger
zap.ReplaceGlobals(l)
return l
}
// Close closes an object and logs an error in case of failure.
func Close(ctx context.Context, obj io.Closer, errorMessage string) {
err := obj.Close()
if err != nil {
FromContext(ctx).Error(errorMessage, zap.Error(err))
}
}