-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogging.go
94 lines (82 loc) · 2.24 KB
/
logging.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
package suzu
import (
"fmt"
"os"
"strings"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/shiguredo/lumberjack/v3"
)
const (
// megabytes
DefaultLogRotateMaxSize = 200
DefaultLogRotateMaxBackups = 7
// days
DefaultLogRotateMaxAge = 30
)
// InitLogger ロガーを初期化する
func InitLogger(config Config) error {
if f, err := os.Stat(config.LogDir); os.IsNotExist(err) || !f.IsDir() {
return err
}
logPath := fmt.Sprintf("%s/%s", config.LogDir, config.LogName)
// https://github.com/rs/zerolog/issues/77
zerolog.TimestampFunc = func() time.Time {
return time.Now().UTC()
}
zerolog.TimeFieldFormat = time.RFC3339Nano
if config.Debug {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
} else {
zerolog.SetGlobalLevel(zerolog.InfoLevel)
}
if config.Debug && config.LogStdout {
writer := zerolog.ConsoleWriter{
Out: os.Stdout,
FormatTimestamp: func(i interface{}) string {
ts, err := time.ParseInLocation("2006-01-02T15:04:05.000000Z", i.(string), time.UTC)
if err != nil {
return fmt.Sprintf("%s", i)
}
return ts.Format("2006-01-02 15:04:05.000000Z07:00:00")
},
}
format(&writer)
log.Logger = zerolog.New(writer).With().Caller().Timestamp().Logger()
} else if config.LogStdout {
writer := os.Stdout
log.Logger = zerolog.New(writer).With().Caller().Timestamp().Logger()
} else {
var logRotateMaxSize, logRotateMaxBackups, logRotateMaxAge int
if config.LogRotateMaxSize == 0 {
logRotateMaxSize = DefaultLogRotateMaxSize
}
if config.LogRotateMaxBackups == 0 {
logRotateMaxBackups = DefaultLogRotateMaxBackups
}
if config.LogRotateMaxAge == 0 {
logRotateMaxAge = DefaultLogRotateMaxAge
}
writer := &lumberjack.Logger{
Filename: logPath,
MaxSize: logRotateMaxSize,
MaxBackups: logRotateMaxBackups,
MaxAge: logRotateMaxAge,
Compress: false,
}
log.Logger = zerolog.New(writer).With().Caller().Timestamp().Logger()
}
return nil
}
func format(w *zerolog.ConsoleWriter) {
w.FormatLevel = func(i interface{}) string {
return strings.ToUpper(fmt.Sprintf("[%s]", i))
}
w.FormatFieldName = func(i interface{}) string {
return fmt.Sprintf("%s=", i)
}
w.FormatFieldValue = func(i interface{}) string {
return fmt.Sprintf("%s", i)
}
}