golang 使用logrus传递ctx

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()
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值