/
log.go
194 lines (166 loc) · 5.38 KB
/
log.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package serverConfig
import (
"errors"
"log"
"net/url"
"os"
"path/filepath"
"time"
commConsts "github.com/easysoft/zentaoatf/internal/pkg/consts"
logUtils "github.com/easysoft/zentaoatf/pkg/lib/log"
"github.com/ergoapi/util/zos"
"gopkg.in/natefinch/lumberjack.v2"
"github.com/snowlyg/helper/dir"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const (
WinFileSchema = "winfile:///"
)
func InitLog() {
CONFIG.Zap.Director = filepath.Join(commConsts.WorkDir, CONFIG.Zap.Director)
if !dir.IsExist(CONFIG.Zap.Director) { // 判断是否有Director文件夹
dir.InsureDir(CONFIG.Zap.Director)
}
zapConfig := getLogConfig()
// print to console and info、err files
var err error
zapConfig.EncoderConfig.EncodeLevel = nil
zapConfig.DisableCaller = true
zapConfig.EncoderConfig.TimeKey = ""
logUtils.LoggerStandard, err = zapConfig.Build()
if err != nil {
log.Println("init console logger fail " + err.Error())
}
logUtils.LoggerStandard = logUtils.LoggerStandard.WithOptions(zap.AddCaller(), zap.AddCallerSkip(1))
// print to console and info、err files without stacktrace detail
// by set DisableStacktrace to true
zapConfig.DisableStacktrace = true
logUtils.LoggerExecConsole, err = zapConfig.Build(zap.WrapCore(zapCoreInFile))
if err != nil {
log.Println("init exec console logger fail " + err.Error())
}
logUtils.LoggerExecConsole = logUtils.LoggerExecConsole.WithOptions(zap.AddCaller(), zap.AddCallerSkip(1))
}
// write exec results by using zap log
func InitExecLog(workspacePath string) {
commConsts.ExecLogDir = logUtils.GetLogDir(workspacePath)
config := getLogConfig()
config.EncoderConfig.EncodeLevel = nil
// print to test log file
logPathInfo := filepath.Join(commConsts.ExecLogDir, commConsts.LogText)
if !zos.IsUnix() {
logPathInfo = filepath.Join(WinFileSchema, logPathInfo)
zap.RegisterSink("winfile", newWinFileSink)
}
config.OutputPaths = []string{logPathInfo}
var err error
logUtils.LoggerExecFile, err = config.Build()
logUtils.LoggerExecFile = logUtils.LoggerExecFile.WithOptions(zap.AddCaller(), zap.AddCallerSkip(1))
if err != nil {
log.Println("init exec file logger fail " + err.Error())
}
config.DisableCaller = true
config.DisableStacktrace = true
config.EncoderConfig.TimeKey = ""
// print to test result file
logPathResult := filepath.Join(commConsts.ExecLogDir, commConsts.ResultText)
if !zos.IsUnix() {
logPathResult = filepath.Join(WinFileSchema, logPathResult)
zap.RegisterSink("winfile", newWinFileSink)
}
config.OutputPaths = []string{logPathResult}
logUtils.LoggerExecResult, err = config.Build()
if err != nil {
log.Println("init exec result logger fail " + err.Error())
}
// logUtils.LoggerExecResult = logUtils.LoggerExecResult.WithOptions(zap.AddCaller(), zap.AddCallerSkip(1))
}
// flush buffer and release the file.
func SyncExecLog() {
if logUtils.LoggerExecFile != nil {
logUtils.LoggerExecFile.Sync()
logUtils.LoggerExecFile = nil
}
if logUtils.LoggerExecResult != nil {
logUtils.LoggerExecResult.Sync()
logUtils.LoggerExecResult = nil
}
}
func getLogConfig() (config zap.Config) {
var level zapcore.Level
switch CONFIG.Zap.Level { // 初始化配置文件的Level
case "debug":
level = zap.DebugLevel
case "info":
level = zap.InfoLevel
case "warn":
level = zap.WarnLevel
case "error":
level = zap.ErrorLevel
case "dpanic":
level = zap.DPanicLevel
case "panic":
level = zap.PanicLevel
case "fatal":
level = zap.FatalLevel
default:
level = zap.InfoLevel
}
encoderConfig := zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "logger",
CallerKey: "caller",
MessageKey: "msg",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeTime: zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000"),
EncodeLevel: zapcore.CapitalColorLevelEncoder, //这里可以指定颜色
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder, // 路径编码器
//EncodeLevel: zapcore.LowercaseLevelEncoder, // 小写编码器
}
config = zap.Config{
Level: zap.NewAtomicLevelAt(level), // 日志级别
Development: true, // 开发模式,堆栈跟踪
Encoding: "console", // 输出格式 console 或 json
EncoderConfig: encoderConfig, // 编码器配置
//InitialFields: map[string]interface{}{"test_machine": "pc1"}, // 初始化字段
}
return
}
func newWinFileSink(u *url.URL) (zap.Sink, error) {
// Remove leading slash left by url.Parse()
var name string
if u.Path != "" {
name = u.Path[1:]
} else if u.Opaque != "" {
name = u.Opaque[1:]
} else {
return nil, errors.New("path error")
}
return os.OpenFile(name, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
}
func zapCoreInFile(c zapcore.Core) zapcore.Core {
logPathInfo := filepath.Join(CONFIG.Zap.Director, "ztf.log")
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.TimeKey = "time"
encoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout(time.RFC3339)
core := zapcore.NewCore(
zapcore.NewJSONEncoder(encoderConfig),
zapcore.NewMultiWriteSyncer(
zapcore.AddSync(&lumberjack.Logger{
Filename: logPathInfo,
LocalTime: true,
MaxSize: 300, // M
MaxAge: 30, // days
MaxBackups: 30,
}),
zapcore.AddSync(os.Stdout),
),
zap.DebugLevel,
)
cores := zapcore.NewTee(c, core)
return cores
}