Нема описа
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.2KB

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