2023-07-14 10:16:58 +08:00
|
|
|
package logger
|
|
|
|
|
|
|
|
import (
|
2023-10-12 10:10:23 +08:00
|
|
|
"log/slog"
|
2023-07-14 10:16:58 +08:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2023-10-12 10:10:23 +08:00
|
|
|
"strings"
|
2023-07-14 10:16:58 +08:00
|
|
|
|
|
|
|
"github.com/natefinch/lumberjack"
|
|
|
|
"joylink.club/bj-rtsts-server/config"
|
|
|
|
)
|
|
|
|
|
2023-10-12 10:10:23 +08:00
|
|
|
const DefaultLogPath = "/var/logs/bjrtsts_server"
|
2023-07-14 10:16:58 +08:00
|
|
|
|
2023-10-12 10:10:23 +08:00
|
|
|
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"
|
2023-07-14 10:16:58 +08:00
|
|
|
}
|
|
|
|
|
2023-10-12 10:10:23 +08:00
|
|
|
// 默认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
|
2023-07-14 10:16:58 +08:00
|
|
|
}
|
|
|
|
|
2023-10-12 10:10:23 +08:00
|
|
|
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,
|
|
|
|
})))
|
2023-07-14 10:16:58 +08:00
|
|
|
}
|
2023-10-12 10:10:23 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// 初始化日志
|
|
|
|
func InitLogger() error {
|
|
|
|
InitSlog()
|
2023-07-14 10:16:58 +08:00
|
|
|
return nil
|
|
|
|
}
|