-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogging.go
91 lines (75 loc) · 2.43 KB
/
logging.go
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
package clarimq
import (
"context"
"log/slog"
)
// Logger is an interface that is be used for log messages.
type Logger interface {
Debug(ctx context.Context, msg string, args ...any)
Error(ctx context.Context, msg string, err error, args ...any)
Info(ctx context.Context, msg string, args ...any)
Warn(ctx context.Context, msg string, args ...any)
}
type logger struct {
loggers []Logger
}
func newLogger(loggers []Logger) *logger {
return &logger{loggers}
}
func (l *logger) logDebug(ctx context.Context, msg string, args ...any) {
for i := range l.loggers {
l.loggers[i].Debug(ctx, msg, args...)
}
}
func (l *logger) logError(ctx context.Context, msg string, err error, args ...any) { //nolint:unparam // thats okay
for i := range l.loggers {
l.loggers[i].Error(ctx, msg, err, args...)
}
}
func (l *logger) logInfo(ctx context.Context, msg string, args ...any) {
for i := range l.loggers {
l.loggers[i].Info(ctx, msg, args...)
}
}
func (l *logger) logWarn(ctx context.Context, msg string, args ...any) {
for i := range l.loggers {
l.loggers[i].Warn(ctx, msg, args...)
}
}
// SlogLogger is a clarimq.Logger implementation that uses slog.Logger.
type SlogLogger struct {
logger *slog.Logger
}
// Debug logs a debug message with the provided attributes.
func (s *SlogLogger) Debug(ctx context.Context, msg string, attrs ...any) {
s.logger.DebugContext(ctx, msg, attrs...)
}
// Info logs an info message with the provided attributes.
func (s *SlogLogger) Info(ctx context.Context, msg string, attrs ...any) {
s.logger.InfoContext(ctx, msg, attrs...)
}
// Warn logs a warning message with the provided attributes.
func (s *SlogLogger) Warn(ctx context.Context, msg string, attrs ...any) {
s.logger.WarnContext(ctx, msg, attrs...)
}
// Error logs an error message with the provided attributes and error.
func (s *SlogLogger) Error(ctx context.Context, msg string, err error, attrs ...any) {
if err != nil {
attrs = append(attrs, "error", err.Error())
}
s.logger.ErrorContext(ctx, msg, attrs...)
}
// NewSlogLogger creates a new instance of SlogLogger.
// If a logger is not provided, it will use the default slog.Logger.
//
// Parameters:
// - logger: A pointer to a slog.Logger instance. If nil, it will use the default logger.
//
// Returns:
// - A new SlogLogger instance that implements the clarimq.Logger.
func NewSlogLogger(logger *slog.Logger) *SlogLogger {
if logger == nil {
logger = slog.Default()
}
return &SlogLogger{logger}
}