-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.go
82 lines (66 loc) · 2.04 KB
/
log.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
/* Package slslog provides the trackable log output with tracing on AWS CloudWatch Logs.
Example:
slslog.SetLogLabel("log label") // e.g. program name
span := slslog.StartSpan(context.Background(), "span label") // e.g. func name
defer span.End()
ctx := span.Context()
Infof(ctx, "this is slslog output")
*/
package slslog
import (
"context"
"fmt"
"log/slog"
"sync"
"github.com/eure/slslog/internal/spancontext"
)
type logger struct {
mu sync.Mutex
label string
c *slog.Logger
}
var std = &logger{
label: "slslog",
c: slog.New(&slsLogHandler{}),
}
func SetLogLabel(label string) {
std.mu.Lock()
defer std.mu.Unlock()
std.label = label
}
func (l *logger) output(ctx context.Context, level slog.Level, format string, a ...interface{}) {
std.mu.Lock()
defer std.mu.Unlock()
sev := level.String()
switch level {
case slog.LevelWarn:
sev = "WARNING"
case levelCritical.Level():
sev = "CRITICAL"
}
msg := fmt.Sprintf(format, a...)
sc := spancontext.Get(ctx)
l.c.LogAttrs(ctx, level, msg,
slog.String("severity", sev),
slog.String("message", msg),
slog.String("trace", fmt.Sprintf("service/%s/trace/%s", l.label, sc.TraceID)),
slog.String("span", fmt.Sprintf("service/%s/span/%s", l.label, sc.SpanID)),
)
}
// Infof formats its arguments according to the format like fmt.Printf,
// and records the text as log message at Info level.
func Infof(ctx context.Context, format string, a ...interface{}) {
std.output(ctx, slog.LevelInfo, format, a...)
}
// Warningf is like Infof, but the severity is warning level.
func Warningf(ctx context.Context, format string, a ...interface{}) {
std.output(ctx, slog.LevelWarn, format, a...)
}
// Errorf is like Infof, but the severity is error level.
func Errorf(ctx context.Context, format string, a ...interface{}) {
std.output(ctx, slog.LevelError, format, a...)
}
// Criticalf is like Infof, but the severity is critical level.
func Criticalf(ctx context.Context, format string, a ...interface{}) {
std.output(ctx, levelCritical.Level(), format, a...)
}