Files
slgserver/log/log.go
2025-11-18 18:08:48 +08:00

47 lines
1.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package log
import (
"io"
"log/slog"
"os"
"path"
"path/filepath"
"slgserver/config"
"strings"
"gopkg.in/natefinch/lumberjack.v2"
)
func init() {
fileDir := config.GetString("log.file_dir", "../log/")
maxSize := config.GetInt("log.max_size", 128)
maxBackups := config.GetInt("log.max_backups", 30)
maxAge := config.GetInt("log.max_age", 7)
compress := config.GetBool("log.compress", true)
sa := strings.Split(filepath.Base(os.Args[0]), ".")
fileName := sa[0] + ".log"
hook := &lumberjack.Logger{
Filename: path.Join(fileDir, fileName), // 日志文件路径
MaxSize: maxSize, // 每个日志文件保存的最大尺寸 单位M
MaxBackups: maxBackups, // 日志文件最多保存多少个备份
MaxAge: maxAge, // 文件最多保存多少天
Compress: compress, // 是否压缩
}
// 创建多写入器:同时写入标准输出和文件
multiWriter := io.MultiWriter(os.Stdout, hook)
// 创建 JSON handler包含调用者信息
opts := &slog.HandlerOptions{
Level: slog.LevelInfo,
AddSource: true, // 添加调用者信息
}
handler := slog.NewJSONHandler(multiWriter, opts)
logger := slog.New(handler)
// 使用 slog 标准方式设置默认 logger
slog.SetDefault(logger)
}