generated from moul/golang-repo-template
-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
zapgorm2_test.go
61 lines (49 loc) · 1.59 KB
/
zapgorm2_test.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
package zapgorm2_test
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
"gorm.io/gorm"
"moul.io/zapgorm2"
)
func Example() {
logger := zapgorm2.New(zap.L())
logger.SetAsDefault() // optional: configure gorm to use this zapgorm.Logger for callbacks
db, _ := gorm.Open(nil, &gorm.Config{Logger: logger})
// do stuff normally
var _ = db // avoid "unused variable" warn
}
func setupLogsCapture() (*zap.Logger, *observer.ObservedLogs) {
core, logs := observer.New(zap.WarnLevel)
return zap.New(core), logs
}
func TestContextFunc(t *testing.T) {
zaplogger, logs := setupLogsCapture()
logger := zapgorm2.New(zaplogger)
type ctxKey string
key1 := ctxKey("Key")
key2 := ctxKey("Key2")
value1 := "Value"
value2 := "Value2"
ctx := context.WithValue(context.Background(), key1, value1)
ctx = context.WithValue(ctx, key2, value2)
logger.Context = func(ctx context.Context) []zapcore.Field {
ctxValue, ok := (ctx.Value(key1)).(string)
require.True(t, ok)
ctxValue2, ok := (ctx.Value(key2)).(string)
require.True(t, ok)
return []zapcore.Field{zap.String(string(key1), ctxValue), zap.String(string(key2), ctxValue2)}
}
db, err := gorm.Open(nil, &gorm.Config{Logger: logger})
require.NoError(t, err)
db.Logger.Error(ctx, "test")
require.Equal(t, 1, logs.Len())
entry := logs.All()[0]
require.Equal(t, zap.ErrorLevel, entry.Level)
require.Equal(t, "test", entry.Message)
require.Equal(t, value1, entry.ContextMap()[string(key1)])
require.Equal(t, value2, entry.ContextMap()[string(key2)])
}