logrus
Logrus 是一个结构化、可插拔的 Go 日志框架,完全兼容官方 log 库接口。功能强大的同时,Logrus
具有高度的灵活性,它提供了自定义插件的功能,有 TEXT 与 JSON 两种可选的日志输出格式。
1. 地址
https://github.com/sirupsen/logrus
2. 示例
由于是在一个大型已有的大型项目上增加日志框架的,因此需要一个全局的logrus实例,即logger对象来记录项目所有的日志。如:
首先,创建一个package,这里我给他起名叫logu:
package logu
import (
"github.com/sirupsen/logrus"
)
然后定义全局变量,定义日志等级
var log *logrus.Logger
func LogInit(logLevel string) {
log = logrus.New()
level := logrus.DebugLevel
log.SetLevel(logrus.ErrorLevel)
switch {
case logLevel == "debug":
level = logrus.DebugLevel
case logLevel == "info":
level = logrus.InfoLevel
case logLevel == "error":
level = logrus.ErrorLevel
default:
level = logrus.DebugLevel
}
log.Formatter = &logrus.JSONFormatter{}
log.SetLevel(level)
}
最后对外提供方法:
func Println(v ...interface{}) {
log.Info(v)
}
func Error(v ...interface{}) {
log.Error(v)
}
func Debug(v ...interface{}) {
log.Debug(v)
}
当然,这里我们只使用了三种日志级别,
logrus原始支持七种:
const (
// PanicLevel level, highest level of severity. Logs and then calls panic with the
// message passed to Debug, Info, ...
PanicLevel Level = iota
// FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the
// logging level is set to Panic.
FatalLevel
// ErrorLevel level. Logs. Used for errors that should definitely be noted.
// Commonly used for hooks to send errors to an error tracking service.
ErrorLevel
// WarnLevel level. Non-critical entries that deserve eyes.
WarnLevel
// InfoLevel level. General operational entries about what's going on inside the
// application.
InfoLevel
// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
DebugLevel
// TraceLevel level. Designates finer-grained informational events than the Debug.
TraceLevel
)
项目启动时,初始化:
logu.LogInit(cfg.Log.Level)