-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog.go
More file actions
272 lines (237 loc) · 8.62 KB
/
log.go
File metadata and controls
272 lines (237 loc) · 8.62 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
/*
* Copyright 2025 The Go-Spring Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package log
import (
"context"
"os"
"runtime"
"time"
)
var (
// defaultLogger is the fallback logger that will be used if no custom logger
// is configured for a specific tag.
defaultLogger Logger = &ConsoleLogger{
LoggerBase: LoggerBase{
Level: LevelRange{
MinLevel: defaultLogLevel(),
MaxLevel: MaxLevel,
},
},
appender: &ConsoleAppender{
AppenderBase: AppenderBase{
Layout: &TextLayout{
BaseLayout: BaseLayout{
FileLineMaxLength: 48,
},
},
},
},
}
// TagAppDef is the default tag for application-related logs.
TagAppDef = RegisterAppTag("def", "")
// TagBizDef is the default tag for business-related logs.
TagBizDef = RegisterBizTag("def", "")
// ReportError is an optional hook function that is invoked whenever an error
// occurs during logging. It can be overridden to handle error reporting, such as
// logging the error to a separate error log or sending alerts.
ReportError = func(err error) {}
// TimeNow is an optional override function that provides a custom timestamp.
// It can be replaced during testing or in special cases where a fixed time
// is required, ensuring consistency in log events across test runs.
TimeNow func(ctx context.Context) time.Time
// StringFromContext is an optional hook to extract a string (e.g., trace ID)
// from the context. This string will be attached to the log event.
// Avoid performing complex calculations in this function.
// It's recommended to use cached results for better performance.
StringFromContext func(ctx context.Context) string
// FieldsFromContext is an optional hook to extract structured fields
// (e.g., trace ID, span ID, or request metadata) from the context.
// Avoid performing complex calculations in this function.
// It's recommended to use cached results for better performance.
FieldsFromContext func(ctx context.Context) []Field
)
// defaultLogLevel returns the default log level for the default logger.
// It checks the environment variable "GS_LOGGER_DEFAULT_LEVEL" and returns
// the corresponding log level. If the environment variable is not set,
// it defaults to InfoLevel.
func defaultLogLevel() Level {
s, ok := os.LookupEnv("GS_LOGGER_DEFAULT_LEVEL")
if !ok {
return InfoLevel
}
r, err := ParseLevelRange(s)
if err != nil {
panic(err) // can panic here
}
return r.MinLevel
}
// RegisterAppTag registers or retrieves a Tag intended for application-layer logs,
// which are typically used to log events related to the application lifecycle,
// such as startup, shutdown, or health checks.
// - subType: component or module name
// - action: lifecycle phase or behavior (optional)
func RegisterAppTag(subType, action string) *Tag {
return RegisterTag(BuildTag("app", subType, action))
}
// RegisterBizTag registers or retrieves a Tag intended for business-logic logs.
// - subType: business domain or feature name
// - action: operation being logged (optional)
func RegisterBizTag(subType, action string) *Tag {
return RegisterTag(BuildTag("biz", subType, action))
}
// RegisterRPCTag registers or retrieves a Tag intended for RPC logs,
// covering external/internal dependency interactions.
// - subType: protocol or target system (e.g., http, grpc, redis)
// - action: RPC phase (e.g., send, retry, fail)
func RegisterRPCTag(subType, action string) *Tag {
return RegisterTag(BuildTag("rpc", subType, action))
}
// getLogger returns the logger associated with the given tag.
// If no logger is bound, the default logger is returned.
func getLogger(tag *Tag) Logger {
if l := tag.logger.Load().Logger; l != nil {
return l
}
return defaultLogger
}
// Trace logs a message at TraceLevel using a lazy field generator.
// The generator function is only invoked if the level is enabled.
func Trace(ctx context.Context, tag *Tag, fn func() []Field) {
if l := getLogger(tag); l.GetLevel().Enable(TraceLevel) {
record(ctx, TraceLevel, tag.tag, l, 2, fn()...)
}
}
// Tracef logs a formatted message at TraceLevel.
func Tracef(ctx context.Context, tag *Tag, format string, args ...any) {
if l := getLogger(tag); l.GetLevel().Enable(TraceLevel) {
record(ctx, TraceLevel, tag.tag, l, 2, Msgf(format, args...))
}
}
// Debug logs a message at DebugLevel using a lazy field generator.
// The generator function is only invoked if the level is enabled.
func Debug(ctx context.Context, tag *Tag, fn func() []Field) {
if l := getLogger(tag); l.GetLevel().Enable(DebugLevel) {
record(ctx, DebugLevel, tag.tag, l, 2, fn()...)
}
}
// Debugf logs a formatted message at DebugLevel.
func Debugf(ctx context.Context, tag *Tag, format string, args ...any) {
if l := getLogger(tag); l.GetLevel().Enable(DebugLevel) {
record(ctx, DebugLevel, tag.tag, l, 2, Msgf(format, args...))
}
}
// Info logs structured fields at InfoLevel.
func Info(ctx context.Context, tag *Tag, fields ...Field) {
if l := getLogger(tag); l.GetLevel().Enable(InfoLevel) {
record(ctx, InfoLevel, tag.tag, l, 2, fields...)
}
}
// Infof logs a formatted message at InfoLevel.
func Infof(ctx context.Context, tag *Tag, format string, args ...any) {
if l := getLogger(tag); l.GetLevel().Enable(InfoLevel) {
record(ctx, InfoLevel, tag.tag, l, 2, Msgf(format, args...))
}
}
// Warn logs structured fields at WarnLevel.
func Warn(ctx context.Context, tag *Tag, fields ...Field) {
if l := getLogger(tag); l.GetLevel().Enable(WarnLevel) {
record(ctx, WarnLevel, tag.tag, l, 2, fields...)
}
}
// Warnf logs a formatted message at WarnLevel.
func Warnf(ctx context.Context, tag *Tag, format string, args ...any) {
if l := getLogger(tag); l.GetLevel().Enable(WarnLevel) {
record(ctx, WarnLevel, tag.tag, l, 2, Msgf(format, args...))
}
}
// Error logs structured fields at ErrorLevel.
func Error(ctx context.Context, tag *Tag, fields ...Field) {
if l := getLogger(tag); l.GetLevel().Enable(ErrorLevel) {
record(ctx, ErrorLevel, tag.tag, l, 2, fields...)
}
}
// Errorf logs a formatted message at ErrorLevel.
func Errorf(ctx context.Context, tag *Tag, format string, args ...any) {
if l := getLogger(tag); l.GetLevel().Enable(ErrorLevel) {
record(ctx, ErrorLevel, tag.tag, l, 2, Msgf(format, args...))
}
}
// Panic logs structured fields at PanicLevel.
func Panic(ctx context.Context, tag *Tag, fields ...Field) {
if l := getLogger(tag); l.GetLevel().Enable(PanicLevel) {
record(ctx, PanicLevel, tag.tag, l, 2, fields...)
}
}
// Panicf logs a formatted message at PanicLevel.
func Panicf(ctx context.Context, tag *Tag, format string, args ...any) {
if l := getLogger(tag); l.GetLevel().Enable(PanicLevel) {
record(ctx, PanicLevel, tag.tag, l, 2, Msgf(format, args...))
}
}
// Fatal logs structured fields at FatalLevel.
func Fatal(ctx context.Context, tag *Tag, fields ...Field) {
if l := getLogger(tag); l.GetLevel().Enable(FatalLevel) {
record(ctx, FatalLevel, tag.tag, l, 2, fields...)
}
}
// Fatalf logs a formatted message at FatalLevel.
func Fatalf(ctx context.Context, tag *Tag, format string, args ...any) {
if l := getLogger(tag); l.GetLevel().Enable(FatalLevel) {
record(ctx, FatalLevel, tag.tag, l, 2, Msgf(format, args...))
}
}
// Record logs a message at the given level for the given tag.
func Record(ctx context.Context, level Level, tag *Tag, skip int, fields ...Field) {
if l := getLogger(tag); l.GetLevel().Enable(level) {
record(ctx, level, tag.tag, l, skip, fields...)
}
}
// record performs the actual logging logic after level checking.
func record(ctx context.Context, level Level, tag string, logger Logger, skip int, fields ...Field) {
var (
file string
line int
)
switch callerType {
case CallerTypeDefault:
_, file, line, _ = runtime.Caller(skip)
case CallerTypeFast:
file, line = FastCaller(skip)
default: // for linter
}
now := time.Now()
if TimeNow != nil {
now = TimeNow(ctx)
}
var ctxString string
if StringFromContext != nil {
ctxString = StringFromContext(ctx)
}
var ctxFields []Field
if FieldsFromContext != nil {
ctxFields = FieldsFromContext(ctx)
}
e := getEvent()
e.Level = level
e.Time = now
e.File = file
e.Line = line
e.Tag = tag
e.Fields = fields
e.CtxString = ctxString
e.CtxFields = ctxFields
logger.Append(e)
}