Brak opisu
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 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package subconfigs
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. // LogConfig 日志配置
  7. type LogConfig struct {
  8. BaseConfig
  9. Level string `yaml:"level"`
  10. Output string `yaml:"output"`
  11. FilePath string `yaml:"file_path"`
  12. MaxSize int `yaml:"max_size"`
  13. MaxBackups int `yaml:"max_backups"`
  14. MaxAge int `yaml:"max_age"`
  15. Compress bool `yaml:"compress"`
  16. //ESEnabled bool `yaml:"es_enabled"`
  17. ESPath string `yaml:"es_path"`
  18. JSONFormat bool `yaml:"json_format"`
  19. }
  20. // NewLogConfig 创建日志配置实例
  21. func NewLogConfig() *LogConfig {
  22. return &LogConfig{}
  23. }
  24. // SetDefaults 设置默认值
  25. func (c *LogConfig) SetDefaults() {
  26. c.Level = "info"
  27. c.Output = "console"
  28. c.FilePath = "logs/service.log"
  29. c.MaxSize = 100
  30. c.MaxBackups = 3
  31. c.MaxAge = 30
  32. c.Compress = true
  33. c.ESPath = "logs/es-service.log"
  34. c.JSONFormat = true
  35. }
  36. // Load 从yaml数据加载
  37. func (c *LogConfig) Load(data map[string]interface{}) error {
  38. return c.LoadFromYAML(data, c)
  39. }
  40. // Validate 验证配置
  41. func (c *LogConfig) Validate() error {
  42. // 验证日志级别
  43. validLevels := map[string]bool{
  44. "debug": true, "info": true, "warn": true, "error": true,
  45. }
  46. if !validLevels[strings.ToLower(c.Level)] {
  47. return fmt.Errorf("invalid log level: %s", c.Level)
  48. }
  49. // 验证输出类型
  50. validOutputs := map[string]bool{
  51. "console": true, "file": true, "both": true,
  52. }
  53. if !validOutputs[c.Output] {
  54. return fmt.Errorf("invalid log output: %s", c.Output)
  55. }
  56. return nil
  57. }
  58. // 自动注册
  59. func init() {
  60. Register("log", &LogConfig{})
  61. }