| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- package subconfigs
-
- import (
- "fmt"
- "strings"
-
- "git.x2erp.com/qdy/go-base/config/core"
- )
-
- // LogConfig 日志配置
- type LogConfig struct {
- core.BaseConfig
- Level string `yaml:"level" json:"level" desc:"日志级别:debug, info, warn, error"`
- Output string `yaml:"output" json:"output" desc:"输出目标:console,file,es"`
- //JSONFormat bool `yaml:"json_format" json:"json_format"` // 是否JSON格式
-
- // 文件输出配置
- FilePath string `yaml:"file_path" json:"file_path" desc:"日志文件路径"`
- MaxSize int `yaml:"max_size" json:"max_size" desc:"单个日志文件最大大小(MB)"`
- MaxBackups int `yaml:"max_backups" json:"max_backups" desc:"最大保留日志文件数"`
- MaxAge int `yaml:"max_age" json:"max_age" desc:"日志文件最大保留天数"`
- Compress bool `yaml:"compress" json:"compress" desc:"是否压缩旧日志文件"`
-
- // ES输出配置(当Output包含"es"时生效)
- ESPath string `yaml:"es_path" json:"es_path" desc:"Elasticsearch地址"`
- ESUsername string `yaml:"es_username" json:"es_username" desc:"Elasticsearch用户名(可选)"`
- ESPassword string `yaml:"es_password" json:"es_password" desc:"Elasticsearch密码(可选)"`
- //ESAPIKey string `yaml:"es_api_key" json:"es_api_key"` // API Key(可选)
- //ESBuffer int `yaml:"es_buffer" json:"es_buffer"` // 缓冲大小,默认10000
- //ESMaxRetry int `yaml:"es_max_retry" json:"es_max_retry"` // 最大重试,默认3
- }
-
- func (c *LogConfig) Description() string {
- return "日志系统配置,支持控制台、文件、Elasticsearch等多种输出方式"
- }
-
- // NewLogConfig 创建日志配置实例
- func NewLogConfig() *LogConfig {
- return &LogConfig{}
- }
-
- // SetDefaults 设置默认值
- func (c *LogConfig) SetDefaults() {
- c.Level = "info"
- c.Output = "console"
- c.FilePath = "logs/service.log"
- c.MaxSize = 100
- c.MaxBackups = 3
- c.MaxAge = 30
- c.Compress = true
- c.ESPath = "logs/es-service.log"
- //c.JSONFormat = true
- }
-
- // Load 从yaml数据加载
- func (c *LogConfig) Load(data map[string]interface{}) error {
- return c.LoadFromYAML(data, c)
- }
-
- // Validate 验证配置
- func (c *LogConfig) Validate() error {
- // 验证日志级别
- validLevels := map[string]bool{
- "debug": true, "info": true, "warn": true, "error": true,
- }
- if !validLevels[strings.ToLower(c.Level)] {
- return fmt.Errorf("invalid log level: %s", c.Level)
- }
-
- // 验证输出类型
- validOutputs := map[string]bool{
- "console": true, "file": true, "both": true,
- }
- if !validOutputs[c.Output] {
- return fmt.Errorf("invalid log output: %s", c.Output)
- }
-
- return nil
- }
-
- // 自动注册
- func init() {
- core.Register("log", &LogConfig{})
- }
|