-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
79 lines (66 loc) · 1.9 KB
/
main.go
File metadata and controls
79 lines (66 loc) · 1.9 KB
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
package main
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"github.com/mengdu/mo"
"gopkg.in/natefinch/lumberjack.v2"
)
type JSONLogger struct {
encoder *json.Encoder
}
func (l *JSONLogger) Log(ctx context.Context, level mo.Level, msg string, kv []mo.Field) {
line := map[string]interface{}{
"level": strings.ToLower(level.String()),
"msg": msg,
}
for _, v := range kv {
line[v.Key()] = v.Value()
}
l.encoder.Encode(line)
}
func main() {
filename := "./logs/app.log"
if err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {
panic(err)
}
out := &lumberjack.Logger{
Filename: filename,
MaxSize: 1, // 最大文件大小 1MB
MaxBackups: 5, // 备份数
MaxAge: 28, // days
Compress: false, // 是否压缩
LocalTime: false,
}
logger := &JSONLogger{
encoder: json.NewEncoder(out),
}
mo.SetRecorder(logger)
mo.SetBase(
mo.Value("ts", mo.Timestamp("15:04:05.000")),
mo.Value("caller", mo.Caller(3)),
mo.Value("tag", "dev"),
)
for i := 0; i < 1000; i++ {
demo()
}
}
func demo() {
mo.Debug("debug message")
mo.Info("info message")
mo.Warn("warn message")
mo.Error("error message")
// mo.Fatal("fatal message")
mo.Debugf("debugf message %s", "test")
mo.Infof("infof message %s", "test")
mo.Warnf("warnf message %s", "test")
mo.Errorf("errorf message %s", "test")
// mo.Fatalf("fatalf message %s", "test")
mo.Debugw("debugw message", mo.Value("k1", 123), mo.Value("k2", true), mo.Value("k3", []int{1, 2, 3}))
mo.Infow("infow message", mo.Value("k1", 123), mo.Value("k2", true), mo.Value("k3", []int{1, 2, 3}))
mo.Warnw("warnw message", mo.Value("k1", 123), mo.Value("k2", true), mo.Value("k3", []int{1, 2, 3}))
mo.Errorw("errorw message", mo.Value("k1", 123), mo.Value("k2", true), mo.Value("k3", []int{1, 2, 3}))
// mo.Fatalw("fatalw message", mo.Value("k1", 123), mo.Value("k2", true), mo.Value("k3", []int{1, 2, 3}))
}