
wzyonggege/loggergithub.com
實作一個基于 uber-go/zap 日志功能的日志檔案歸檔子產品
- 分級歸檔,可按info/error分開存放日志
- 按日志檔案大小歸檔
- 按時間間隔歸
1. 分級歸檔
zap 本身支援日志分級,在寫入檔案的時候選擇好輸出路徑
2. 按檔案大小
檔案大小切割借助了第三方庫 lumberjack ,可以選擇檔案的大小來切割
(LogOptions 中存放一些配置)
func (c *LogOptions) sizeDivisionWriter(filename string) io.Writer {
hook := &lumberjack.Logger{
Filename: filename,
MaxSize: c.MaxSize,
MaxBackups: c.MaxBackups,
MaxAge: c.MaxSize,
Compress: c.Compress,
}
return hook
}
3. 按時間切割
按時間切割可是借助到了第三方的庫file-rotatelogs
func (c *LogOptions) timeDivisionWriter(filename string) io.Writer {
hook, err := rotatelogs.New(
filename+c.TimeUnit.Format(),
rotatelogs.WithMaxAge(time.Duration(int64(24*time.Hour)*int64(c.MaxAge))),
rotatelogs.WithRotationTime(c.TimeUnit.RotationGap()),
)
if err != nil {
panic(err)
}
return hook
}
LogOptions的TimeUnit可以選擇切割單元,例如按小時切割的日志為server.log.2019091123
4. 使用
c := logger.New()
c.SetDivision("time") // 設定歸檔方式,"time"時間歸檔 "size" 檔案大小歸檔,檔案大小等可以在配置檔案配置
c.SetTimeUnit(logde.Minute) // 時間歸檔 可以設定切割機關
c.SetEncoding("json") // 輸出格式 "json" 或者 "console"
c.SetInfoFile("./logs/server.log") // 設定info級别日志
c.SetErrorFile("./logs/server_err.log") // 設定warn級别日志
c.InitLogger()
logger.Info("info level test")
logger.Info("this is a log", logger.With("Trace", "12345677")) // 帶參數
logger.Error("this is a log", logger.WithError("error", errors.New("this is a new error"))) // 帶error
5. Benchmark
再寫個簡單的benchmark
BenchmarkLogger/logde_logger_without_fields-4 3000000 563 ns/op
BenchmarkLogger/logde_logger_with_fields-4 2000000 637 ns/op
BenchmarkLogger/logde_logger_without_fields_write_into_file-4 200000 13021 ns/op
BenchmarkLogger/logde_logger_with_fields_write_into_file-4 100000 12606 ns/op
6. 結尾
放上 GitHub 位址: https://github.com/wzyonggege/logger
寫得粗略,慢慢改改。