2021-12-14 10:53:50 +08:00
|
|
|
|
package logger
|
|
|
|
|
|
|
|
|
|
import (
|
2021-12-29 14:33:48 +08:00
|
|
|
|
"fmt"
|
|
|
|
|
"github.com/caarlos0/env/v6"
|
2021-12-14 10:53:50 +08:00
|
|
|
|
"go.uber.org/zap"
|
|
|
|
|
"go.uber.org/zap/zapcore"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var config LogConfig
|
|
|
|
|
var Say *zap.SugaredLogger
|
|
|
|
|
|
2021-12-14 11:08:57 +08:00
|
|
|
|
// 避免异常,在第一次调用时初始化一个只打印到控制台的logger
|
|
|
|
|
func init() {
|
2021-12-15 09:21:08 +08:00
|
|
|
|
if Say == nil {
|
2021-12-29 14:33:48 +08:00
|
|
|
|
// 从环境变量读取配置
|
|
|
|
|
var c LogConfig
|
|
|
|
|
if err := env.Parse(&c); err != nil {
|
|
|
|
|
fmt.Println("日志配置解析错误: " + err.Error())
|
|
|
|
|
c = LogConfig{Mode: Dev, LokiEnable: false, FileEnable: false}
|
|
|
|
|
}
|
|
|
|
|
InitLogger(c)
|
2021-12-15 09:21:08 +08:00
|
|
|
|
}
|
2021-12-14 11:08:57 +08:00
|
|
|
|
}
|
|
|
|
|
|
2021-12-14 10:53:50 +08:00
|
|
|
|
// InitLogger 初始化日志工具
|
|
|
|
|
func InitLogger(c LogConfig) {
|
|
|
|
|
config = c
|
|
|
|
|
var cores []zapcore.Core
|
|
|
|
|
// 生成输出到控制台的Core
|
|
|
|
|
consoleCore := initConsoleCore()
|
|
|
|
|
cores = append(cores, consoleCore)
|
|
|
|
|
// 生成输出到Loki的Core
|
|
|
|
|
if config.LokiEnable {
|
|
|
|
|
lokiCore := initLokiCore()
|
|
|
|
|
cores = append(cores, lokiCore)
|
|
|
|
|
}
|
|
|
|
|
// 输出到文件的Core
|
|
|
|
|
if config.FileEnable {
|
|
|
|
|
fileCore := initFileCore()
|
|
|
|
|
cores = append(cores, fileCore)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 增加 caller 信息
|
2022-05-18 11:07:30 +08:00
|
|
|
|
// AddCallerSkip 输出的文件名和行号是调用封装函数的位置,而不是调用日志函数的位置
|
|
|
|
|
logger := zap.New(zapcore.NewTee(cores...), zap.AddCaller(), zap.AddCallerSkip(1))
|
2021-12-14 10:53:50 +08:00
|
|
|
|
Say = logger.Sugar()
|
2022-05-18 10:42:45 +08:00
|
|
|
|
zap.ReplaceGlobals(logger)
|
2021-12-14 10:53:50 +08:00
|
|
|
|
}
|