-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmylog_test.go
102 lines (89 loc) · 1.95 KB
/
mylog_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
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
// Copyright (c) 2022 hxx258456
// github.com/hxx258456/mylog is licensed under Mulan PSL v2.
package mylog_test
import (
"errors"
"io/ioutil"
"os"
"path"
"testing"
"github.com/bxcodec/faker/v3"
"github.com/hxx258456/mylog"
"gopkg.in/natefinch/lumberjack.v2"
)
var filePath = "../testdata/test.log"
func TestLogStrcut(t *testing.T) {
data := struct {
Name string
Age int64
}{
Name: "bob",
Age: 32,
}
log := mylog.New(os.Stdout)
log.Print(data)
}
func TestLogToFile(t *testing.T) {
data := struct {
Name string
Age int64
}{
Name: "bob",
Age: 32,
}
filePath := filePath
file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777)
if err != nil {
t.Error(err)
}
// colorWrite := NewConsoleWriter()
log := mylog.New(file)
log.Info().Timestamp().Interface("data", data).Msg("test")
}
// rotate log
func TestRotateLog(t *testing.T) {
log := mylog.New(&lumberjack.Logger{
Filename: filePath,
MaxSize: 1, // 单个文件大小
MaxBackups: 3, // 旧日志文件的数量
MaxAge: 28, // 日志存活时长
Compress: true, // 压缩
LocalTime: true,
})
for i := 0; i < 100000; i++ {
log.Info().Timestamp().Msg("test")
}
}
// clean test
func TestClean(t *testing.T) {
t.Cleanup(func() {
dir, err := ioutil.ReadDir("../testdata")
if err != nil {
t.Error(err)
}
for _, d := range dir {
os.RemoveAll(path.Join("../testdata", d.Name()))
}
})
}
func BenchmarkLog(b *testing.B) {
str := faker.Paragraph()
file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777)
if err != nil {
b.Error(err)
}
// colorWrite := NewConsoleWriter()
log := mylog.New(file).With().Timestamp().Caller().Logger()
b.Run("stack", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
log.Info().Str("message", str).Send()
}
})
b.Run("error", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
log.Error().Err(errors.New(str)).Send()
}
})
}