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
|
package cmd
import (
"bytes"
"context"
"log"
"log/slog"
"os"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestLogFormat(t *testing.T) {
os.Unsetenv("GOMPLATE_LOG_FORMAT")
assert.Equal(t, "json", logFormat(nil))
// os.Stdout isn't a terminal when this runs as a unit test...
assert.Equal(t, "json", logFormat(os.Stdout))
t.Setenv("GOMPLATE_LOG_FORMAT", "simple")
assert.Equal(t, "simple", logFormat(os.Stdout))
assert.Equal(t, "simple", logFormat(&bytes.Buffer{}))
}
// a slog handler that strips the 'time' field
type noTimestampHandler struct {
slog.Handler
}
var _ slog.Handler = (*noTimestampHandler)(nil)
func (h *noTimestampHandler) Handle(ctx context.Context, r slog.Record) error {
r.Time = time.Time{}
return h.Handler.Handle(ctx, r)
}
func TestCreateLogHandler(t *testing.T) {
buf := &bytes.Buffer{}
h := createLogHandler("", buf, slog.LevelWarn)
// strip the 'time' field for easier comparison
h = &noTimestampHandler{h}
l := slog.New(h)
slog.SetDefault(l)
l.Debug("this won't show up")
l.Warn("hello world")
actual := strings.TrimSpace(buf.String())
assert.JSONEq(t, `{"level":"WARN","msg":"hello world"}`, actual)
buf.Reset()
h = createLogHandler("simple", buf, slog.LevelDebug)
l = slog.New(h)
slog.SetDefault(l)
l.Debug("this will show up", "field", "a value")
log.Println("hello world")
actual = strings.TrimSpace(buf.String())
assert.Equal(t, "this will show up field=\"a value\"\n hello world", actual)
buf.Reset()
h = createLogHandler("console", buf, slog.LevelDebug)
h = &noTimestampHandler{h}
l = slog.New(h)
slog.SetDefault(l)
l.Debug("hello")
log.Println("world")
actual = strings.TrimSpace(buf.String())
assert.Equal(t, "DBG hello\nINF world", actual)
buf.Reset()
h = createLogHandler("logfmt", buf, slog.LevelInfo)
h = &noTimestampHandler{h}
l = slog.New(h)
slog.SetDefault(l)
l.Info("hello\"", "field", "a value", "num", 84)
actual = strings.TrimSpace(buf.String())
assert.Equal(t, "level=INFO msg=\"hello\\\"\" field=\"a value\" num=84", actual)
}
|