github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/logger/config.go (about)

     1  package logger
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/volts-dev/volts/config"
     7  )
     8  
     9  type (
    10  	Option func(*Config)
    11  
    12  	Config struct {
    13  		config.Config `field:"-"`
    14  		Name          string `field:"-"` // config name/path in config file
    15  		PrefixName    string `field:"-"` // config prefix name
    16  		Level         Level
    17  		//Prefix         string
    18  		WriterName string
    19  	}
    20  )
    21  
    22  var (
    23  	creators = make(map[string]IWriterType) // 注册的Writer类型函数接口
    24  )
    25  
    26  func newConfig(opts ...Option) *Config {
    27  	cfg := &Config{
    28  		//Config: config.Default(),
    29  		Level: LevelDebug,
    30  		Name:  "logger",
    31  	}
    32  	cfg.Init(opts...)
    33  	config.Register(cfg)
    34  	return cfg
    35  }
    36  
    37  func (self *Config) String() string {
    38  	if len(self.PrefixName) > 0 {
    39  		return strings.Join([]string{self.Name, self.PrefixName}, ".")
    40  	}
    41  	return self.Name
    42  }
    43  
    44  func (self *Config) Init(opts ...Option) {
    45  	for _, opt := range opts {
    46  		if opt != nil {
    47  			opt(self)
    48  		}
    49  	}
    50  }
    51  func (self *Config) Load() error {
    52  	return self.LoadToModel(self)
    53  }
    54  
    55  func (self *Config) Save(immed ...bool) error {
    56  	return self.SaveFromModel(self, immed...)
    57  }
    58  
    59  func Debug() Option {
    60  	return func(cfg *Config) {
    61  		cfg.Debug = true
    62  	}
    63  }
    64  
    65  func WithWrite(name string) Option {
    66  	return func(cfg *Config) {
    67  		cfg.WriterName = name
    68  	}
    69  }
    70  
    71  // 修改Config.json的路径
    72  func WithConfigPrefixName(prefixName string) Option {
    73  	return func(cfg *Config) {
    74  		cfg.Unregister(cfg)
    75  		cfg.PrefixName = prefixName
    76  		cfg.Register(cfg)
    77  		// 重新加载
    78  		//cfg.Load()
    79  	}
    80  }
    81  
    82  func WithLevel(lvl Level) Option {
    83  	return func(cfg *Config) {
    84  		cfg.Level = lvl
    85  	}
    86  }