github.com/songzhibin97/gkit@v1.2.13/log/logger.go (about)

     1  package log
     2  
     3  import (
     4  	"context"
     5  	"log"
     6  )
     7  
     8  // DefaultLogger is default logger.
     9  var DefaultLogger Logger = NewStdLogger(log.Writer())
    10  
    11  // Logger 操作日志对外的接口
    12  // 实现该接口需要保证它是并发安全的
    13  type Logger interface {
    14  	Log(lever Lever, kv ...interface{}) error
    15  }
    16  
    17  type logger struct {
    18  	// log: 输出对象
    19  	logs []Logger
    20  	// prefix: kv键值对 构建前缀
    21  	prefix []interface{}
    22  	// hasValuer 判断是否包含 Valuer 类型
    23  	hasValuer bool
    24  	// ctx 上下文
    25  	ctx context.Context
    26  }
    27  
    28  // Log 实现 Logger 接口
    29  func (l *logger) Log(lever Lever, kvs ...interface{}) error {
    30  	nKvs := make([]interface{}, 0, len(l.prefix)+len(kvs))
    31  	nKvs = append(nKvs, l.prefix...)
    32  	if l.hasValuer && len(kvs) > 0 {
    33  		// 特殊处理
    34  		bindValues(l.ctx, nKvs)
    35  	}
    36  	if len(kvs) > 0 {
    37  		nKvs = append(nKvs, kvs...)
    38  	}
    39  
    40  	for _, log := range l.logs {
    41  		if err := log.Log(lever, nKvs...); err != nil {
    42  			return err
    43  		}
    44  	}
    45  	return nil
    46  }
    47  
    48  // With 生成 Logger
    49  func With(l Logger, kvs ...interface{}) Logger {
    50  	if c, ok := l.(*logger); ok {
    51  		nKvs := make([]interface{}, 0, len(c.prefix)+len(kvs))
    52  		nKvs = append(kvs, kvs...)
    53  		nKvs = append(kvs, c.prefix...)
    54  		return &logger{
    55  			logs:      c.logs,
    56  			prefix:    kvs,
    57  			hasValuer: containsValuer(nKvs),
    58  			ctx:       c.ctx,
    59  		}
    60  	}
    61  	return &logger{logs: []Logger{l}, prefix: kvs, hasValuer: containsValuer(kvs)}
    62  }
    63  
    64  // WithContext 设置 Logger 上下文
    65  func WithContext(ctx context.Context, l Logger) Logger {
    66  	if c, ok := l.(*logger); ok {
    67  		return &logger{
    68  			logs:      c.logs,
    69  			prefix:    c.prefix,
    70  			hasValuer: c.hasValuer,
    71  			ctx:       ctx,
    72  		}
    73  	}
    74  	return &logger{logs: []Logger{l}, ctx: ctx}
    75  }
    76  
    77  // WithLogs 包装多个 Logger
    78  func WithLogs(logs ...Logger) Logger {
    79  	return &logger{logs: logs}
    80  }