github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/core/common/logger/logging.go (about)

     1  package logger
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/zbh255/bilog"
     6  	"os"
     7  	"sync/atomic"
     8  )
     9  
    10  const (
    11  	OpenLogger  int64 = 1 << 10
    12  	CloseLogger int64 = 1 << 11
    13  )
    14  
    15  type LLogger interface {
    16  	Info(format string, v ...interface{})
    17  	Debug(format string, v ...interface{})
    18  	Warn(format string, v ...interface{})
    19  	Error(format string, v ...interface{})
    20  	Panic(format string, v ...interface{})
    21  }
    22  
    23  var DefaultLogger LLogger
    24  
    25  type LLoggerImpl struct {
    26  	loggerOpen int64
    27  	logging    bilog.Logger
    28  }
    29  
    30  func New(l bilog.Logger) LLogger {
    31  	return &LLoggerImpl{logging: l, loggerOpen: OpenLogger}
    32  }
    33  
    34  func (c *LLoggerImpl) Debug(format string, v ...interface{}) {
    35  	if !c.ReadLoggerStatus() {
    36  		return
    37  	}
    38  	c.logging.Debug(fmt.Sprintf(format, v...))
    39  }
    40  
    41  func (c *LLoggerImpl) Info(format string, v ...interface{}) {
    42  	if !c.ReadLoggerStatus() {
    43  		return
    44  	}
    45  	c.logging.Info(fmt.Sprintf(format, v...))
    46  }
    47  
    48  func (c *LLoggerImpl) Warn(format string, v ...interface{}) {
    49  	if !c.ReadLoggerStatus() {
    50  		return
    51  	}
    52  	c.logging.Trace(fmt.Sprintf(format, v...))
    53  }
    54  
    55  func (c *LLoggerImpl) Error(format string, v ...interface{}) {
    56  	if !c.ReadLoggerStatus() {
    57  		return
    58  	}
    59  	c.logging.ErrorFromString(fmt.Sprintf(format, v...))
    60  }
    61  
    62  func (c *LLoggerImpl) Panic(format string, v ...interface{}) {
    63  	if !c.ReadLoggerStatus() {
    64  		return
    65  	}
    66  	c.logging.PanicFromString(fmt.Sprintf(format, v...))
    67  }
    68  
    69  func (c *LLoggerImpl) ReadLoggerStatus() bool {
    70  	return atomic.LoadInt64(&c.loggerOpen) == OpenLogger
    71  }
    72  
    73  func SetOpenLogger(ok bool) {
    74  	logger, typeOk := DefaultLogger.(*LLoggerImpl)
    75  	if !typeOk {
    76  		return
    77  	}
    78  	if ok {
    79  		atomic.StoreInt64(&logger.loggerOpen, OpenLogger)
    80  	} else {
    81  		atomic.StoreInt64(&logger.loggerOpen, CloseLogger)
    82  	}
    83  }
    84  
    85  func init() {
    86  	SetOpenLogger(true)
    87  	bilogLogger := bilog.NewLogger(
    88  		os.Stdout, bilog.PANIC,
    89  		bilog.WithTimes(),
    90  		bilog.WithCaller(1),
    91  		bilog.WithLowBuffer(0),
    92  		bilog.WithTopBuffer(0),
    93  	)
    94  	DefaultLogger = &LLoggerImpl{
    95  		logging: bilogLogger,
    96  	}
    97  }