rts-sim-testing-service/logger/logger.go

65 lines
1.8 KiB
Go
Raw Normal View History

package logger
import (
"log/slog"
"os"
"path/filepath"
"strings"
"github.com/natefinch/lumberjack"
"joylink.club/bj-rtsts-server/config"
)
const DefaultLogPath = "/var/logs/bjrtsts_server"
func InitSlog() {
logging := config.Config.Logging
slog.Debug("读取日志配置内容", "logging", logging)
// 判断日志路径是否存在,如果不存在就创建
if strings.Trim(logging.Path, " ") == "" {
logging.Path = DefaultLogPath
}
// 日志文件 与 日志切割 配置
if strings.Trim(logging.FileName, " ") == "" {
logging.FileName = "server.log"
}
// 默认Info
level := slog.LevelInfo
if strings.ToUpper(logging.Level) == "DEBUG" {
level = slog.LevelDebug
} else if strings.ToUpper(logging.Level) == "WARN" {
level = slog.LevelWarn
} else if strings.ToUpper(logging.Level) == "ERROR" {
level = slog.LevelError
}
if logging.Stdout {
// 日志输出到控制台
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: level,
AddSource: false,
})))
} else {
// 日志输出到日志文件(自动滚动)
lumberJackLogger := &lumberjack.Logger{
Filename: filepath.Join(logging.Path, logging.FileName), // 日志文件路径
MaxSize: logging.FileMaxSize, // 单个日志文件最大多少 mb
MaxBackups: logging.FileMaxBackups, // 日志备份数量
MaxAge: logging.MaxAge, // 日志最长保留时间
LocalTime: true, // 日志备份使用本地时间
Compress: logging.Compress, // 是否压缩日志
}
slog.SetDefault(slog.New(slog.NewJSONHandler(lumberJackLogger, &slog.HandlerOptions{
Level: level,
AddSource: false,
})))
}
}
// 初始化日志
func InitLogger() error {
InitSlog()
return nil
}