log: add logrus log lib and add telegram notification push as an option

This commit is contained in:
tangmengqiu
2025-11-04 23:48:32 -05:00
parent 8d36a5affa
commit 61d45ebb0e
10 changed files with 648 additions and 21 deletions

64
logger/config.go Normal file
View File

@@ -0,0 +1,64 @@
package logger
import (
"github.com/sirupsen/logrus"
)
// Config 日志配置(简化版)
type Config struct {
Level string `json:"level"` // 日志级别: debug, info, warn, error (默认: info)
Telegram *TelegramConfig `json:"telegram"` // Telegram推送配置可选
}
// TelegramConfig Telegram推送配置简化版高级参数使用默认值
type TelegramConfig struct {
Enabled bool `json:"enabled"` // 是否启用(默认: false
BotToken string `json:"bot_token"` // Bot Token
ChatID int64 `json:"chat_id"` // Chat ID
MinLevel string `json:"min_level"` // 最低日志级别该级别及以上的日志会推送到Telegram可选默认: error
}
// SetDefaults 设置默认值
func (c *Config) SetDefaults() {
if c.Level == "" {
c.Level = "info"
}
}
// GetLogrusLevels 返回要推送到Telegram的日志级别
// 根据配置的MinLevel返回该级别及以上的所有日志级别
// 如果未配置或配置无效默认返回error, fatal, panic向后兼容
func (tc *TelegramConfig) GetLogrusLevels() []logrus.Level {
// 如果未配置使用默认值error向后兼容
minLevelStr := tc.MinLevel
if minLevelStr == "" {
minLevelStr = "error"
}
// 解析配置的日志级别
minLevel, err := logrus.ParseLevel(minLevelStr)
if err != nil {
// 如果解析失败使用默认值error向后兼容
minLevel = logrus.ErrorLevel
}
// 定义所有日志级别从高到低panic, fatal, error, warn, info, debug
allLevels := []logrus.Level{
logrus.PanicLevel,
logrus.FatalLevel,
logrus.ErrorLevel,
logrus.WarnLevel,
logrus.InfoLevel,
logrus.DebugLevel,
}
// 返回所有大于等于minLevel的日志级别
var result []logrus.Level
for _, level := range allLevels {
if level <= minLevel {
result = append(result, level)
}
}
return result
}