美文网首页
golang常用代码片段--定制化log组件

golang常用代码片段--定制化log组件

作者: 江江的大猪 | 来源:发表于2019-11-24 23:38 被阅读0次
    • 使用logrus配合file-rotatelogs、lfshook实现:
      1 日志文件按时间切割
      2 根据日志等级输出到不同文件
      3 增加默认的日志信息(比如本文中的本机ip,获取本机ip的代码就不贴了)
    
    const (
        _infoPath = "info.log"
        _errorPath = "error.log"
        _rotationHour = 24
        _maxAgeHour = 72
        _timeStampFormat = "2016-01-02 15:04:05"
    )
    var _logEntry *logrus.Entry
    func init() {
        log := logrus.StandardLogger()
        _logEntry = log.WithField("localIp", utils.GetLocalIp())
        log.SetFormatter(&logrus.TextFormatter{
            DisableColors:   true,
            TimestampFormat: _timeStampFormat,
        })
        // 不向控制台打印
        //log.Out = ioutil.Discard
        // 写文件不加锁,具体参考logrus文档确认可不可以不锁
        // log.SetNoLock()
        infoWriter, err := rotatelogs.New(
            _infoPath+".%Y-%m-%d",
            rotatelogs.WithLinkName(_infoPath),
            rotatelogs.WithRotationTime(time.Hour*_rotationHour),
            rotatelogs.WithMaxAge(time.Hour*_maxAgeHour),
        )
        if err != nil {
            panic(err)
        }
        errorWriter, err := rotatelogs.New(
            _errorPath+".%Y-%m-%d",
            rotatelogs.WithLinkName(_errorPath),
            rotatelogs.WithRotationTime(time.Hour*_rotationHour),
            rotatelogs.WithMaxAge(time.Hour*_maxAgeHour),
        )
        if err != nil {
            panic(err)
        }
        allWriter := io.MultiWriter(infoWriter, errorWriter)
        log.AddHook(lfshook.NewHook(
            lfshook.WriterMap{
                logrus.InfoLevel:  infoWriter,
                logrus.ErrorLevel: allWriter,
                logrus.PanicLevel: allWriter,
            },
            &logrus.TextFormatter{
                DisableColors:   true,
                TimestampFormat: _timeStampFormat,
            },
        ))
    }
    
    func WithField(key string, value interface{}) *logrus.Entry {
        return _logEntry.WithField(key, value)
    }
    
    func Info(args ...interface{}) {
        _logEntry.Info(args...)
    }
    
    func Infof(format string, args ...interface{}) {
        _logEntry.Infof(format, args...)
    }
    
    func Error(args ...interface{}) {
        _logEntry.Error(args...)
    }
    
    func Errorf(format string, args ...interface{}) {
        _logEntry.Errorf(format, args...)
    }
    
    func Panic(args ...interface{}) {
        _logEntry.Panic(args...)
    }
    
    func Panicf(format string, args ...interface{}) {
        _logEntry.Panicf(format, args...)
    }
    

    相关文章

      网友评论

          本文标题:golang常用代码片段--定制化log组件

          本文链接:https://www.haomeiwen.com/subject/ajgrwctx.html