-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson_sync.go
More file actions
381 lines (336 loc) · 8.64 KB
/
Copy pathjson_sync.go
File metadata and controls
381 lines (336 loc) · 8.64 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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package logger
import (
"encoding/json"
"errors"
"fmt"
"log"
"os"
"strings"
"time"
)
// LogLevel represents the minimum log severity threshold
type LogLevel int
const (
LevelDebug LogLevel = iota // 0
LevelInfo // 1
LevelWarn // 2
LevelError // 3
LevelFatal // 4
)
// RedactConfig defines field redaction rules and censor replacement string
type RedactConfig struct {
Paths []string `json:"paths"`
Censor string `json:"censor"`
}
// DefaultRedactConfig returns default redaction settings for sensitive fields
func DefaultRedactConfig() *RedactConfig {
return &RedactConfig{
Paths: []string{
"password",
"card",
"token",
"refresh_token",
"*.password",
"*.card",
"*.token",
"req.headers.authorization",
},
Censor: "[Redacted]",
}
}
// JSONConfig holds the base metadata configuration for JSON log entries
type JSONConfig struct {
DeviceID string
AppVersion string
Service string
LogLevel LogLevel // LevelDebug, LevelInfo, LevelWarn, LevelError, LevelFatal
PrettyPrint bool
Redact *RedactConfig
}
// LogEntry defines the JSON structure for log outputs
type LogEntry struct {
Timestamp string `json:"timestamp"`
Level string `json:"level"`
DeviceID string `json:"device_id,omitempty"`
AppVersion string `json:"app_version,omitempty"`
TraceID string `json:"trace_id,omitempty"`
Service string `json:"service,omitempty"`
Msg string `json:"msg"`
Data any `json:"data,omitempty"`
}
type redactor struct {
paths []string
censor string
}
func newRedactor(paths []string, censor string) *redactor {
if censor == "" {
censor = "[Redacted]"
}
return &redactor{
paths: paths,
censor: censor,
}
}
func (r *redactor) shouldRedact(key string, fullPath string) bool {
keyLower := strings.ToLower(key)
fullPathLower := strings.ToLower(fullPath)
for _, p := range r.paths {
pLower := strings.ToLower(strings.TrimSpace(p))
if pLower == "" {
continue
}
if strings.HasPrefix(pLower, "*.") {
target := pLower[2:]
if keyLower == target || strings.HasSuffix(fullPathLower, "."+target) {
return true
}
} else if strings.Contains(pLower, ".") {
if fullPathLower == pLower {
return true
}
} else {
if keyLower == pLower || fullPathLower == pLower {
return true
}
}
}
return false
}
func redactAny(val any, currentPath string, r *redactor) any {
if val == nil || r == nil {
return val
}
switch v := val.(type) {
case map[string]any:
newMap := make(map[string]any, len(v))
for k, item := range v {
itemPath := k
if currentPath != "" {
itemPath = currentPath + "." + k
}
if r.shouldRedact(k, itemPath) {
newMap[k] = r.censor
} else {
newMap[k] = redactAny(item, itemPath, r)
}
}
return newMap
case []any:
newSlice := make([]any, len(v))
for i, item := range v {
newSlice[i] = redactAny(item, currentPath, r)
}
return newSlice
default:
return val
}
}
func normalizeData(data any) any {
if data == nil {
return nil
}
switch data.(type) {
case map[string]any, []any, string, int, int64, float64, bool:
return data
default:
b, err := json.Marshal(data)
if err != nil {
return data
}
var out any
if err := json.Unmarshal(b, &out); err != nil {
return data
}
return out
}
}
// RedactData applies field redaction rules to data payloads
func RedactData(data any, config *RedactConfig) any {
if data == nil || config == nil || len(config.Paths) == 0 {
return data
}
censor := config.Censor
if censor == "" {
censor = "[Redacted]"
}
r := newRedactor(config.Paths, censor)
normalized := normalizeData(data)
return redactAny(normalized, "", r)
}
// JSONLogEntry represents an active JSON log entry allowing .TraceID() and .Data() chaining
type JSONLogEntry struct {
logger *LoggerSyncJSON
entry LogEntry
enabled bool
}
// TraceID updates the trace_id of the log entry
func (e *JSONLogEntry) TraceID(traceID string) *JSONLogEntry {
if !e.enabled {
return e
}
e.entry.TraceID = traceID
e.logger.printEntry(e.entry)
return e
}
// Data updates the data payload of the log entry
func (e *JSONLogEntry) Data(data any) *JSONLogEntry {
if !e.enabled {
return e
}
e.entry.Data = data
e.logger.printEntry(e.entry)
return e
}
// LoggerSyncJSON handles synchronous JSON logging
type LoggerSyncJSON struct {
config JSONConfig
writeFileEnable bool
objectName string
file *os.File
fileName string
path string
}
// NewSyncJSON creates a new synchronous JSON logger instance
func NewSyncJSON(config JSONConfig) *LoggerSyncJSON {
logger := &LoggerSyncJSON{
config: config,
writeFileEnable: false,
}
log.SetOutput(os.Stdout)
log.SetFlags(0)
return logger
}
func (l *LoggerSyncJSON) baseEntry(level string, msg string) LogEntry {
return LogEntry{
Timestamp: time.Now().Format("2006-01-02T15:04:05.000Z07:00"),
Level: level,
DeviceID: l.config.DeviceID,
AppVersion: l.config.AppVersion,
Service: l.config.Service,
Msg: msg,
}
}
func (l *LoggerSyncJSON) shouldLog(level LogLevel) bool {
return level >= l.config.LogLevel
}
func (l *LoggerSyncJSON) printEntry(entry LogEntry) {
if l.config.Redact != nil {
entry.Data = RedactData(entry.Data, l.config.Redact)
}
var bytes []byte
var err error
if l.config.PrettyPrint {
bytes, err = json.MarshalIndent(entry, "", " ")
} else {
bytes, err = json.Marshal(entry)
}
var formattedMsg string
if err != nil {
formattedMsg = fmt.Sprintf(`{"timestamp":"%s","level":"ERROR","msg":"failed to marshal log entry: %v"}`,
time.Now().Format("2006-01-02T15:04:05.000Z07:00"), err)
} else {
formattedMsg = string(bytes)
}
if l.writeFileEnable && l.file != nil {
l.file.WriteString(formattedMsg + "\n")
}
log.Println(formattedMsg)
}
func (l *LoggerSyncJSON) createEntry(level string, levelVal LogLevel, msg string) *JSONLogEntry {
if !l.shouldLog(levelVal) {
return &JSONLogEntry{
logger: l,
enabled: false,
}
}
entry := l.baseEntry(level, msg)
l.printEntry(entry)
return &JSONLogEntry{
logger: l,
entry: entry,
enabled: true,
}
}
// Logging methods
func (l *LoggerSyncJSON) Debug(a ...any) *JSONLogEntry {
return l.createEntry("DEBUG", LevelDebug, fmt.Sprint(a...))
}
func (l *LoggerSyncJSON) Debugf(format string, a ...any) *JSONLogEntry {
return l.createEntry("DEBUG", LevelDebug, fmt.Sprintf(format, a...))
}
func (l *LoggerSyncJSON) Info(a ...any) *JSONLogEntry {
return l.createEntry("INFO", LevelInfo, fmt.Sprint(a...))
}
func (l *LoggerSyncJSON) Infof(format string, a ...any) *JSONLogEntry {
return l.createEntry("INFO", LevelInfo, fmt.Sprintf(format, a...))
}
func (l *LoggerSyncJSON) Warn(a ...any) *JSONLogEntry {
return l.createEntry("WARN", LevelWarn, fmt.Sprint(a...))
}
func (l *LoggerSyncJSON) Warnf(format string, a ...any) *JSONLogEntry {
return l.createEntry("WARN", LevelWarn, fmt.Sprintf(format, a...))
}
func (l *LoggerSyncJSON) Error(a ...any) *JSONLogEntry {
return l.createEntry("ERROR", LevelError, fmt.Sprint(a...))
}
func (l *LoggerSyncJSON) Errorf(format string, a ...any) *JSONLogEntry {
return l.createEntry("ERROR", LevelError, fmt.Sprintf(format, a...))
}
func (l *LoggerSyncJSON) Panic(a ...any) {
msg := fmt.Sprint(a...)
if l.shouldLog(LevelError) {
entry := l.baseEntry("PANIC", msg)
l.printEntry(entry)
}
panic(msg)
}
func (l *LoggerSyncJSON) Panicf(format string, a ...any) {
msg := fmt.Sprintf(format, a...)
if l.shouldLog(LevelError) {
entry := l.baseEntry("PANIC", msg)
l.printEntry(entry)
}
panic(msg)
}
func (l *LoggerSyncJSON) Fatal(a ...any) {
msg := fmt.Sprint(a...)
if l.shouldLog(LevelFatal) {
entry := l.baseEntry("FATAL", msg)
l.printEntry(entry)
}
os.Exit(1)
}
func (l *LoggerSyncJSON) Fatalf(format string, a ...any) {
msg := fmt.Sprintf(format, a...)
if l.shouldLog(LevelFatal) {
entry := l.baseEntry("FATAL", msg)
l.printEntry(entry)
}
os.Exit(1)
}
// File persistence and rotation
func (l *LoggerSyncJSON) SetWriteFilesEnable(path string, objectName string) {
l.objectName = objectName
l.path = newFolderPath(path)
l.fileName = fileNameGenerator(l.objectName)
l.file = createAndAppendObject(l.fileName, path)
l.writeFileEnable = true
}
func (l *LoggerSyncJSON) ChangeFileRoutine(hour int, minute int) error {
if !l.writeFileEnable {
return errors.New("set write files enable first")
}
go func() {
for range time.Tick(1 * time.Minute) {
hours, minutes, _ := time.Now().Clock()
if hours == hour && minutes == minute {
if l.file != nil {
l.file.Close()
}
l.fileName = fileNameGenerator(l.objectName)
l.file = createAndAppendObject(l.fileName, l.path)
}
}
}()
return nil
}