logrus日志级别
logrus日志一共7级别, 从高到低: panic, fatal, error, warn, info, debug, trace.
logrus.SetLevel(logrus.InfoLevel)
logrus.SetLevel(logrus.DebugLevel)
...
logrus调用方式
logrus总共提供两种方式调用:
1、logrus.Info("hello logrus")
2、logrus.WithField(logruns.Fields{"key":"value"}).Info("hello logrus")
logrus打印格式
默认情况下就是TextFormatter, 默认情况下是带颜色输出的.
TextFormatter格式
func main() {
logrus.SetFormatter(&log.TextFormatter{})
logrus.Info("hello logrus")
}
打印如下:
INFO[0000] hello logrus
JSONFormatter格式
func main() {
logrus.SetFormatter(&log.JSONFormatter{})
logrus.Info("hello logrus")
}
打印如下:
{"level":"info","msg":"hello logrus","time":"2020-07-11T22:47:14+08:00"}
logrus打印颜色
当然也不是任何时候都输出带颜色的结果, 取决于在终端输出并且不是运行在windows系统, 或者是否设置过ForceColors=true, 如果设置了就会按照有颜色的方式输出
logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true, FullTimestamp: true})
logrus向下延用
第一层调用:定义log结构
import log "github.com/sirupsen/logrus"
func First() {
var (
ok bool
logctx *logrus.Entry
)
if log, ok = ctx.Value(utils.LoggerStr).(*logrus.Entry); !ok {
logctx = logrus.WithFields(logrus.Fields{
"error": "no_error",
"func": "First"})
}
// 通过ctx传递log
Second(ctx)
}
第二场调用:子函数若未收到则追加,然后补充log参数
import log "github.com/sirupsen/logrus"
func GetLogrus(ctx context.Context, funName string) *logrus.Entry {
logCtx, ok := ctx.Value(LoggerStr).(*logrus.Entry)
if !ok {
logCtx = logrus.WithFields(logrus.Fields{
"error": "no_error",
"func": funName})
}
return logCtx
}
func Second (ctx context.Context) {
logctx :=GetLogrus(ctx, "Second")
logctx = logctx.WithFields(logrus.Fields{"add": "Second"})
ctx = context.WithValue(ctx, utils.LoggerStr, logctx)
}
主函数:
import log "github.com/sirupsen/logrus"
func init () {
logrus.SetLevel(logrus.InfoLevel)
logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true, FullTimestamp: true})
}
func main () {
init()
First()
}