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

     1  package logger
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"os"
     7  	"strings"
     8  	"sync"
     9  )
    10  
    11  type (
    12  	ILogger interface {
    13  		GetLevel() Level
    14  		SetLevel(l Level)
    15  
    16  		Assert(cnd bool, format string, args ...interface{})
    17  
    18  		Panicf(format string, v ...interface{})
    19  		Fatalf(string, ...interface{})
    20  		Dbgf(format string, v ...interface{})
    21  		Atkf(format string, v ...interface{})
    22  		Errf(format string, v ...interface{}) error
    23  		Warnf(format string, v ...interface{})
    24  		Infof(format string, v ...interface{})
    25  		Tracef(format string, v ...interface{})
    26  
    27  		//Panic(v ...interface{})
    28  		Panic(v ...interface{})
    29  		Fatal(...interface{})
    30  		Dbg(v ...interface{})
    31  		Atk(v ...interface{})
    32  		Err(v ...interface{}) error
    33  		Warn(v ...interface{})
    34  		Info(v ...interface{})
    35  		Trace(v ...interface{})
    36  	}
    37  
    38  	// Supply API to user
    39  	TLogger struct {
    40  		Config  *Config
    41  		manager *TWriterManager
    42  	}
    43  )
    44  
    45  var (
    46  	loggers       sync.Map
    47  	defaultLogger = New("volts")
    48  )
    49  
    50  // the output like: 2035/01/01 00:00:00 [Prefix][Action] message...
    51  func New(Prefix string, opts ...Option) *TLogger {
    52  	Prefix = strings.ToLower(Prefix)
    53  	if l, ok := loggers.Load(Prefix); ok {
    54  		return l.(*TLogger)
    55  	}
    56  
    57  	opts = append(opts, WithConfigPrefixName(Prefix)) //
    58  	config := newConfig(opts...)
    59  
    60  	//log := newLogger(opts...)
    61  	log := &TLogger{
    62  		Config: config,
    63  	}
    64  	log.manager = &TWriterManager{
    65  		writer:              make(map[string]IWriter),
    66  		level_writer:        make(map[Level]IWriter),
    67  		config:              config,
    68  		msg:                 make(chan *TWriterMsg, 10000), //10000 means the number of messages in chan.
    69  		loggerFuncCallDepth: 2,
    70  	}
    71  
    72  	//go log.manager.listen()
    73  
    74  	log.manager.writer["Console"] = NewConsoleWriter()
    75  	log.manager.writerName = "Console"
    76  
    77  	// 缓存池新建对象函数
    78  	log.manager.msgPool = &sync.Pool{
    79  		New: func() interface{} {
    80  			return &TWriterMsg{}
    81  		},
    82  	}
    83  
    84  	loggers.Store(Prefix, log)
    85  	return log
    86  }
    87  
    88  // Register makes a log provide available by the provided name.
    89  // If Register is called twice with the same name or if driver is nil,
    90  // it panics.
    91  func RegisterWriter(name string, aWriterCreator IWriterType) {
    92  	name = strings.ToLower(name)
    93  	if aWriterCreator == nil {
    94  		panic("logs: Register provide is nil")
    95  	}
    96  	if _, dup := creators[name]; dup {
    97  		panic("logs: Register called twice for provider " + name)
    98  	}
    99  	creators[name] = aWriterCreator
   100  }
   101  
   102  func Get(profix string) ILogger {
   103  	v, ok := loggers.Load(profix)
   104  	if ok {
   105  		return v.(ILogger)
   106  	}
   107  	return nil
   108  }
   109  
   110  func Set(profix string, log ILogger) {
   111  	loggers.Store(profix, log)
   112  }
   113  
   114  func All() []ILogger {
   115  	var logs []ILogger
   116  	loggers.Range(func(key, value interface{}) bool {
   117  		logs = append(logs, value.(ILogger))
   118  		return true
   119  	})
   120  	return logs
   121  }
   122  
   123  // 断言!如果条件成立报告错误
   124  func Assert(cnd bool, format string, args ...interface{}) {
   125  	if cnd {
   126  		panic(fmt.Sprintf(format, args...))
   127  	}
   128  }
   129  
   130  // Returns true if the given level is at or lower the current logger level
   131  func Lvl(level Level, log ...ILogger) bool {
   132  	var l ILogger = defaultLogger
   133  	if len(log) > 0 {
   134  		l = log[0]
   135  	}
   136  	return l.GetLevel() <= level
   137  }
   138  
   139  func Atkf(fmt string, arg ...interface{}) {
   140  	defaultLogger.Atkf(fmt, arg...)
   141  }
   142  
   143  func Info(err ...interface{}) {
   144  	defaultLogger.Info(err...)
   145  }
   146  
   147  func Infof(fmt string, arg ...interface{}) {
   148  	defaultLogger.Infof(fmt, arg...)
   149  }
   150  
   151  func Warn(err ...interface{}) {
   152  	defaultLogger.Warn(err...)
   153  }
   154  
   155  func Warnf(fmt string, arg ...interface{}) {
   156  	defaultLogger.Warnf(fmt, arg...)
   157  }
   158  
   159  func Dbg(err ...interface{}) {
   160  	defaultLogger.Dbg(err...)
   161  }
   162  
   163  func Dbgf(fmt string, arg ...interface{}) {
   164  	defaultLogger.Dbgf(fmt, arg...)
   165  }
   166  
   167  func Err(err ...interface{}) error {
   168  	return defaultLogger.Err(err...)
   169  }
   170  
   171  func Errf(fmt string, arg ...interface{}) error {
   172  	return defaultLogger.Errf(fmt, arg...)
   173  }
   174  
   175  func Panicf(format string, args ...interface{}) {
   176  	panic(fmt.Sprintf(format, args...))
   177  }
   178  
   179  func Fatal(args ...interface{}) {
   180  	defaultLogger.Fatal(args...)
   181  }
   182  
   183  func Fatalf(format string, args ...interface{}) {
   184  	defaultLogger.Fatalf(format, args...)
   185  }
   186  
   187  func PanicErr(err error, title ...string) bool {
   188  	if err != nil {
   189  		defaultLogger.Dbg(err)
   190  		panic(err)
   191  		//panic("[" + title[0] + "] " + err.Error())
   192  	}
   193  	return false
   194  }
   195  
   196  func LogErr(err error, title ...string) bool {
   197  	if err != nil {
   198  		//defaultLogger.ErrorLn(err)
   199  		if len(title) > 0 {
   200  			defaultLogger.Err("[" + title[0] + "] " + err.Error())
   201  		} else {
   202  			defaultLogger.Err(err.Error())
   203  		}
   204  
   205  		return true
   206  	}
   207  	return false
   208  }
   209  
   210  // SetLogger provides a given logger creater into Logger with config string.
   211  // config need to be correct JSON as string: {"interval":360}.
   212  func (self *TLogger) SetWriter(name string, config string) error {
   213  	var wt IWriter
   214  	var has bool
   215  	name = strings.ToLower(name)
   216  	self.manager.lock.Lock()
   217  	defer self.manager.lock.Unlock()
   218  
   219  	if wt, has = self.manager.writer[name]; !has {
   220  		if creater, has := creators[name]; has {
   221  			wt = creater()
   222  		} else {
   223  			return fmt.Errorf("Logger.SetLogger: unknown creater %q (forgotten Register?)", name)
   224  		}
   225  	}
   226  
   227  	err := wt.Init(config)
   228  	if err != nil {
   229  		fmt.Println("Logger.SetLogger: " + err.Error())
   230  		return err
   231  	}
   232  	self.manager.writer[name] = wt
   233  	self.manager.writerName = name
   234  	return nil
   235  }
   236  
   237  // 设置不同等级使用不同警报方式
   238  func (self *TLogger) SetLevelWriter(level Level, writer IWriter) {
   239  	if level > -1 && writer != nil {
   240  		self.manager.level_writer[level] = writer
   241  	}
   242  }
   243  
   244  // remove a logger adapter in BeeLogger.
   245  func (self *TLogger) RemoveWriter(name string) error {
   246  	self.manager.lock.Lock()
   247  	defer self.manager.lock.Unlock()
   248  	if wt, has := self.manager.writer[name]; has {
   249  		wt.Destroy()
   250  		delete(self.manager.writer, name)
   251  	} else {
   252  		return fmt.Errorf("Logger.RemoveWriter: unknown writer %v (forgotten Register?)", self)
   253  	}
   254  	return nil
   255  }
   256  
   257  func (self *TLogger) GetLevel() Level {
   258  	return self.manager.config.Level
   259  }
   260  
   261  func (self *TLogger) SetLevel(level Level) {
   262  	self.manager.config.Level = level
   263  }
   264  
   265  // Async set the log to asynchronous and start the goroutine
   266  func (self *TLogger) Async(aSwitch ...bool) *TLogger {
   267  	if len(aSwitch) > 0 {
   268  		self.manager.asynchronous = aSwitch[0]
   269  	} else {
   270  		self.manager.asynchronous = true
   271  	}
   272  
   273  	// 避免多次运行 Go 程
   274  	if self.manager.asynchronous {
   275  		go self.manager.listen()
   276  	}
   277  
   278  	return self
   279  }
   280  
   281  // 断言如果结果和条件不一致就错误
   282  func (self *TLogger) Assert(condition bool, format string, args ...interface{}) {
   283  	if condition {
   284  		panic(fmt.Sprintf(format, args...))
   285  	}
   286  }
   287  
   288  // enable log funcCallDepth
   289  func (self *TLogger) EnableFuncCallDepth(b bool) {
   290  	self.manager.lock.Lock()
   291  	defer self.manager.lock.Unlock()
   292  	self.manager.enableFuncCallDepth = b
   293  }
   294  
   295  // set log funcCallDepth
   296  func (self *TLogger) SetLogFuncCallDepth(aDepth int) {
   297  	self.manager.loggerFuncCallDepth = aDepth
   298  }
   299  
   300  /*
   301  // Log EMERGENCY level message.
   302  func (self *TLogger) Emergency(format string, v ...interface{}) {
   303  	msg := fmt.Sprintf("[M] "+format, v...)
   304  	self.manager.writerMsg(LevelEmergency, msg)
   305  }
   306  
   307  // Log ALERT level message.
   308  func (self *TLogger) Alert(format string, v ...interface{}) {
   309  	msg := fmt.Sprintf("[A] "+format, v...)
   310  	self.manager.writerMsg(LevelAlert, msg)
   311  }
   312  
   313  // Log CRITICAL level message.
   314  func (self *TLogger) Critical(format string, v ...interface{}) {
   315  	msg := fmt.Sprintf("[C] "+format, v...)
   316  	self.manager.writerMsg(LevelCritical, msg)
   317  }
   318  */
   319  
   320  // Log INFORMATIONAL level message.
   321  func (self *TLogger) Infof(format string, v ...interface{}) {
   322  	msg := fmt.Sprintf("[INFO] "+format, v...)
   323  	self.manager.write(LevelInfo, msg)
   324  }
   325  
   326  func (self *TLogger) Panicf(format string, args ...interface{}) {
   327  	msg := fmt.Sprintf("[PANIC] "+format, args...)
   328  	self.manager.write(LevelAlert, msg)
   329  	panic(msg)
   330  }
   331  
   332  func (self *TLogger) Fatalf(format string, args ...interface{}) {
   333  	msg := fmt.Sprintf("[FATAL] "+format, args...)
   334  	self.manager.write(LevelAlert, msg)
   335  	os.Exit(1)
   336  }
   337  
   338  // Log WARNING level message.
   339  func (self *TLogger) Warnf(format string, v ...interface{}) {
   340  	msg := fmt.Sprintf("[WARM] "+format, v...)
   341  	self.manager.write(LevelWarn, msg)
   342  }
   343  
   344  // Log ERROR level message.
   345  func (self *TLogger) Errf(format string, v ...interface{}) error {
   346  	msg := fmt.Errorf("[ERR] "+format, v...)
   347  	self.manager.write(LevelError, msg.Error())
   348  	return msg
   349  }
   350  
   351  // Log DEBUG level message.
   352  func (self *TLogger) Dbgf(format string, v ...interface{}) {
   353  	msg := fmt.Sprintf("[DBG] "+format, v...)
   354  	self.manager.write(LevelDebug, msg)
   355  }
   356  
   357  func (self *TLogger) Tracef(format string, v ...interface{}) {
   358  	msg := fmt.Sprintf("[TRACE] "+format, v...)
   359  	self.manager.write(LevelTrace, msg)
   360  }
   361  
   362  // Log Attack level message.
   363  func (self *TLogger) Atkf(format string, v ...interface{}) {
   364  	msg := fmt.Sprintf("[ATK] "+format, v...)
   365  	self.manager.write(LevelAttack, msg)
   366  }
   367  
   368  // Log INFORMATIONAL level message.
   369  func (self *TLogger) Info(v ...interface{}) {
   370  	msg := fmt.Sprint(v...)
   371  	self.manager.write(LevelInfo, "[INFO] "+msg)
   372  }
   373  
   374  // Log WARNING level message.
   375  func (self *TLogger) Warn(v ...interface{}) {
   376  	msg := fmt.Sprint(v...)
   377  	self.manager.write(LevelWarn, "[WARM] "+msg)
   378  }
   379  
   380  // Log ERROR level message.
   381  func (self *TLogger) Err(v ...interface{}) error {
   382  	// not print nil error message
   383  	if v != nil && v[0] == nil {
   384  		return nil
   385  	}
   386  
   387  	msg := fmt.Sprint(v...)
   388  	self.manager.write(LevelError, "[ERR] "+msg)
   389  	return errors.New(msg)
   390  }
   391  
   392  func (self *TLogger) Panic(args ...interface{}) {
   393  	msg := fmt.Sprint(args...)
   394  	self.manager.write(LevelWarn, "[PANIC] "+msg)
   395  	panic(msg)
   396  }
   397  
   398  func (self *TLogger) Fatal(v ...interface{}) {
   399  	msg := fmt.Sprint(v...)
   400  	self.manager.write(LevelAlert, "[FATAL] "+msg)
   401  	os.Exit(1)
   402  }
   403  
   404  // Log DEBUG level message.
   405  func (self *TLogger) Dbg(v ...interface{}) {
   406  	msg := fmt.Sprint(v...)
   407  	self.manager.write(LevelDebug, "[DBG] "+msg)
   408  }
   409  
   410  // Log Trace level message.
   411  func (self *TLogger) Trace(v ...interface{}) {
   412  	msg := fmt.Sprint(v...)
   413  	self.manager.write(LevelTrace, "[TRACE] "+msg)
   414  }
   415  
   416  // Log Attack level message.
   417  func (self *TLogger) Atk(v ...interface{}) {
   418  	msg := fmt.Sprint(v...)
   419  	self.manager.write(LevelAttack, "[ATK] "+msg)
   420  }
   421  
   422  /*
   423  // flush all chan data.
   424  func (self *TLogger) Flush() {
   425  	for _, l := range self.manager.writer {
   426  		l.Flush()
   427  	}
   428  }
   429  
   430  // close logger, flush all chan data and destroy all adapters in TLogger.
   431  func (self *TLogger) Close() {
   432  	for {
   433  		if len(self.msg) > 0 {
   434  			bm := <-self.msg
   435  			for _, l := range self.outputs {
   436  				err := l.write(bm.msg, bm.level)
   437  				if err != nil {
   438  					fmt.Println("ERROR, unable to write (while closing logger):", err)
   439  				}
   440  			}
   441  		} else {
   442  			break
   443  		}
   444  	}
   445  	for _, l := range self.outputs {
   446  		l.Flush()
   447  		l.Destroy()
   448  	}
   449  }
   450  */