21. 资源库 - zap.loggger

日志概述

日志的级别从低到高可分为:

  • debug
  • info
  • warn
  • error
  • fatal

实际使用中可根据不同的场景,使用不同级别的日志来记录。

使用日志框架的目的:

一般程序语言自带的日志函数,在效率、易用性及功能上并不能满足项目需求,所以通常需要借助第三方日志框架来实现。

这次我们选择使用 uber 的日志框架 zap。

Zap 简介

Blazing fast, structured, leveled logging in Go.

Zap 用法实例

func init() {
	var core zapcore.Core
	hook := lumberjack.Logger{
		Filename:   "./logs/rs.log",
		MaxSize:    100, // megabytes
		MaxBackups: 3,
		MaxAge:     7,    //days
		Compress:   true, // disabled by default
		LocalTime:  true,
	}

	fileWriter := zapcore.AddSync(&hook)
	consoleDebugging := zapcore.Lock(os.Stdout)

	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoder := zapcore.NewJSONEncoder(encoderConfig)

	// Join the outputs, encoders, and level-handling functions into
	// zapcore.Cores, then tee the four cores together.
	highPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
		return lvl >= zapcore.InfoLevel
	})
	lowPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
		return lvl >= zapcore.DebugLevel
	})

	core = zapcore.NewTee(
		zapcore.NewCore(encoder, consoleDebugging, lowPriority),
		zapcore.NewCore(encoder, fileWriter, highPriority),
	)
	caller := zap.AddCaller()
	callerSkipOpt := zap.AddCallerSkip(1)
	// From a zapcore.Core, it's easy to construct a Logger.
	zapLogger = zap.New(core, caller, callerSkipOpt, zap.AddStacktrace(zap.ErrorLevel))
}

func main()  {
	defer zapLogger.Sync()
	zapLogger.Info("print info msg", zap.String("say", "hello world"))
	zapLogger.Debug("print debug msg", zap.String("say", "hello"))
}

上述代码实例实现了:

  • rolling log
  • 根据不同的日志级别输出的不同的地方
  • structured output message

教程参考:http://vearne.cc/archives/649

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值