github.com/jtzjtz/kit@v1.0.2/log/handler.go (about)

     1  package log
     2  
     3  import (
     4  	"sync"
     5  )
     6  
     7  type LogLevel int8
     8  
     9  const (
    10  	ACCESSLEVEL LogLevel = iota //accesslog级别
    11  
    12  	INFOLEVEL //info日志级别
    13  
    14  	ERRORLEVEL //error 日志级别
    15  )
    16  
    17  type logEntity struct {
    18  	LogLevel LogLevel
    19  	LogData  interface{}
    20  }
    21  
    22  var logChannel chan logEntity
    23  var openFileGroup sync.Map
    24  
    25  //初始化异步日志通道
    26  func initHandler(handlerCnt, channelCnt int) {
    27  	logChannel = make(chan logEntity, channelCnt)
    28  	for i := 0; i < handlerCnt; i++ {
    29  		go handleLog()
    30  	}
    31  }
    32  
    33  //异步写日志方法
    34  func handleLog() {
    35  	defer func() {
    36  		if err := recover(); err != nil {
    37  			println("handle log err", err)
    38  		}
    39  	}()
    40  
    41  	for logEntity := range logChannel {
    42  
    43  		if Logger == nil {
    44  			println("Logger 日志实例为空")
    45  
    46  		}
    47  		switch logEntity.LogLevel {
    48  
    49  		case ACCESSLEVEL:
    50  			Logger.Debugw("access", "logdata", logEntity.LogData)
    51  			break
    52  		case INFOLEVEL:
    53  			Logger.Infow("info", "logdata", logEntity.LogData)
    54  			break
    55  		case ERRORLEVEL:
    56  			Logger.Errorw("error", "logdata", logEntity.LogData)
    57  			break
    58  		default:
    59  			println("logEntity.LogLevel 类型不匹配")
    60  		}
    61  	}
    62  }