Geen omschrijving
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

log_config.go 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package subconfigs
  2. import (
  3. "fmt"
  4. "strings"
  5. "git.x2erp.com/qdy/go-base/config/core"
  6. )
  7. // LogConfig 日志配置
  8. type LogConfig struct {
  9. core.BaseConfig
  10. Level string `yaml:"level" json:"level" desc:"日志级别:debug, info, warn, error"`
  11. Output string `yaml:"output" json:"output" desc:"输出目标:console,file,es"`
  12. //JSONFormat bool `yaml:"json_format" json:"json_format"` // 是否JSON格式
  13. // 文件输出配置
  14. FilePath string `yaml:"file_path" json:"file_path" desc:"日志文件路径"`
  15. MaxSize int `yaml:"max_size" json:"max_size" desc:"单个日志文件最大大小(MB)"`
  16. MaxBackups int `yaml:"max_backups" json:"max_backups" desc:"最大保留日志文件数"`
  17. MaxAge int `yaml:"max_age" json:"max_age" desc:"日志文件最大保留天数"`
  18. Compress bool `yaml:"compress" json:"compress" desc:"是否压缩旧日志文件"`
  19. // ES输出配置(当Output包含"es"时生效)
  20. ESPath string `yaml:"es_path" json:"es_path" desc:"Elasticsearch地址"`
  21. ESUsername string `yaml:"es_username" json:"es_username" desc:"Elasticsearch用户名(可选)"`
  22. ESPassword string `yaml:"es_password" json:"es_password" desc:"Elasticsearch密码(可选)"`
  23. //ESAPIKey string `yaml:"es_api_key" json:"es_api_key"` // API Key(可选)
  24. //ESBuffer int `yaml:"es_buffer" json:"es_buffer"` // 缓冲大小,默认10000
  25. //ESMaxRetry int `yaml:"es_max_retry" json:"es_max_retry"` // 最大重试,默认3
  26. }
  27. func (c *LogConfig) Description() string {
  28. return "日志系统配置,支持控制台、文件、Elasticsearch等多种输出方式"
  29. }
  30. // NewLogConfig 创建日志配置实例
  31. func NewLogConfig() *LogConfig {
  32. return &LogConfig{}
  33. }
  34. // SetDefaults 设置默认值
  35. func (c *LogConfig) SetDefaults() {
  36. c.Level = "info"
  37. c.Output = "console"
  38. c.FilePath = "logs/service.log"
  39. c.MaxSize = 100
  40. c.MaxBackups = 3
  41. c.MaxAge = 30
  42. c.Compress = true
  43. c.ESPath = "logs/es-service.log"
  44. //c.JSONFormat = true
  45. }
  46. // Load 从yaml数据加载
  47. func (c *LogConfig) Load(data map[string]interface{}) error {
  48. return c.LoadFromYAML(data, c)
  49. }
  50. // Validate 验证配置
  51. func (c *LogConfig) Validate() error {
  52. // 验证日志级别
  53. validLevels := map[string]bool{
  54. "debug": true, "info": true, "warn": true, "error": true,
  55. }
  56. if !validLevels[strings.ToLower(c.Level)] {
  57. return fmt.Errorf("invalid log level: %s", c.Level)
  58. }
  59. // 验证输出类型
  60. validOutputs := map[string]bool{
  61. "console": true, "file": true, "both": true,
  62. }
  63. if !validOutputs[c.Output] {
  64. return fmt.Errorf("invalid log output: %s", c.Output)
  65. }
  66. return nil
  67. }
  68. // 自动注册
  69. func init() {
  70. core.Register("log", &LogConfig{})
  71. }