Goland中使用zap日志库


运行下面的命令安装zap

go get -u go.uber.org/zap
一 简单的logger实例

通过调用zap.NewProduction()/zap.NewDevelopment()或者zap.Example()创建一个Logger

在性能很好但不是很关键的上下文中,使用SugaredLogger。它比其他结构化日志记录包快4-10倍,并且支持结构化和printf风格的日志记录。

在每一微秒和每一次内存分配都很重要的上下文中,使用Logger。它甚至比SugaredLogger更快,内存分配次数也更少,但它只支持强类型的结构化日志记录。

package mainimport ("github.com/gin-gonic/gin""go.uber.org/zap"
)
// 两种类型的日志记录器sugarlogger 和logger
var sugarlogger *zap.SugaredLogger
var logger *zap.Loggerfunc main() {InitLogger()defer sugarlogger.Sync()r := gin.Default()r.GET("/sugerlogger", func(c *gin.Context) {sugarlogger.Info("sugerlogger:访问了sugerlogger")logger.Info("logger:访问了sugerlogger")})_ = r.Run(":8888")
}
func InitLogger() {// zap.NewExample() 用于测试//{"level":"info","msg":"sugerlogger:访问了sugerlogger"}//zap.NewProduction() 用于生产环境//{"level":"info","ts":"2021-09-22T20:17:15.979+0800","caller":"zap_log_demo/SugaredLoggerDemo.go:16","msg":"sugerlogger:访问了sugerlogger"}//zap.NewDevelopment() 用户开发环境//2021-09-22T20:17:53.011+0800  INFO    zap_log_demo/SugaredLoggerDemo.go:16    sugerlogger:访问了sugerloggerlogger, _ = zap.NewDevelopment()sugarlogger = logger.Sugar()
}
二 、定制logger

将日志写入文件而不是终端

我们将使用 zap.new()方法配置

package mainimport ("github.com/gin-gonic/gin""go.uber.org/zap""go.uber.org/zap/zapcore""os"
)var sugarlogger *zap.SugaredLogger
//日志格式
func getEncoder() zapcore.Encoder {// 以下两种都是EncoderConfig类型 可以使用源码中封装的 也可以自定义// zap.NewProductionEncoderConfig()// zap.NewDevelopmentEncoderConfig()// return zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())//自定义 我们可以修改里面的key和value值实现日志的定制encodingConfig := zapcore.EncoderConfig{TimeKey:        "ts",LevelKey:       "level",NameKey:        "logger",CallerKey:      "caller",FunctionKey:    zapcore.OmitKey,MessageKey:     "msg",StacktraceKey:  "stacktrace",LineEnding:     zapcore.DefaultLineEnding,EncodeLevel:    zapcore.LowercaseLevelEncoder,EncodeTime:     zapcore.ISO8601TimeEncoder, //时间格式更改EncodeDuration: zapcore.SecondsDurationEncoder,EncodeCaller:   zapcore.ShortCallerEncoder,}return  zapcore.NewJSONEncoder(encodingConfig)}
// 日志写到哪里
func getWriteSyncer() zapcore.WriteSyncer {file, _ := os.OpenFile("path", os.O_CREATE|os.O_APPEND, 666)return zapcore.AddSync(file)
}
func InitLogger() {// zapcore.Core需要三个配置——Encoder,WriteSyncer,LogLevelencoder := getEncoder()writerSync := getWriteSyncer()core := zapcore.NewCore(encoder, writerSync, zapcore.DebugLevel)//logger := zap.New(core)//添加AddCaller方法可以查看那个文件那一行调用了该日志//{"level":"info","ts":"2021-09-22T22:26:03.874+0800","caller":"go_zap_new/zap定制logger.go:55","msg":"Success...状态码200"}logger := zap.New(core,zap.AddCaller())sugarlogger = logger.Sugar()
}func main() {InitLogger()defer sugarlogger.Sync()r := gin.Default()r.GET("/sugerlogger", func(c *gin.Context) {sugarlogger.Info("自定义的log:访问了sugerlogger")})_ = r.Run(":8888")
}
三、日志切割

目前来说日志全是写在一个文件里的 当所有的日志全在一个文件里的时候 查阅是不友好的

安装

go get -u github.com/natefinch/lumberjack

使用

由于是文件的切割 所以我们只修改getWriteSyncer方法

func getWriteSyncer() zapcore.WriteSyncer {lumberJackLogger := &lumberjack.Logger{Filename:   "./go_zap_loglib/selflog.log", //文件位置MaxSize:    10,//在进行切割之前,日志文件的最大大小(以MB为单位)MaxBackups: 5, //保留旧文件的最大个数MaxAge:     30, // 保留旧文件的最大天数Compress:   false,// 是否压缩/归档旧文件}return zapcore.AddSync(lumberJackLogger)
}
四、分析源码 logger如何创建的
//默认的EncoderConfig结构
type EncoderConfig struct {// Set the keys used for each log entry. If any key is empty, that portion// of the entry is omitted.MessageKey    string `json:"messageKey" yaml:"messageKey"`LevelKey      string `json:"levelKey" yaml:"levelKey"`TimeKey       string `json:"timeKey" yaml:"timeKey"`NameKey       string `json:"nameKey" yaml:"nameKey"`CallerKey     string `json:"callerKey" yaml:"callerKey"`FunctionKey   string `json:"functionKey" yaml:"functionKey"`StacktraceKey string `json:"stacktraceKey" yaml:"stacktraceKey"`LineEnding    string `json:"lineEnding" yaml:"lineEnding"`// Configure the primitive representations of common complex types. For// example, some users may want all time.Times serialized as floating-point// seconds since epoch, while others may prefer ISO8601 strings.EncodeLevel    LevelEncoder    `json:"levelEncoder" yaml:"levelEncoder"`EncodeTime     TimeEncoder     `json:"timeEncoder" yaml:"timeEncoder"`EncodeDuration DurationEncoder `json:"durationEncoder" yaml:"durationEncoder"`EncodeCaller   CallerEncoder   `json:"callerEncoder" yaml:"callerEncoder"`// Unlike the other primitive type encoders, EncodeName is optional. The// zero value falls back to FullNameEncoder.EncodeName NameEncoder `json:"nameEncoder" yaml:"nameEncoder"`// Configures the field separator used by the console encoder. Defaults// to tab.ConsoleSeparator string `json:"consoleSeparator" yaml:"consoleSeparator"`
}//默认的config配置
type Config struct {// Level is the minimum enabled logging level. Note that this is a dynamic// level, so calling Config.Level.SetLevel will atomically change the log// level of all loggers descended from this config.Level AtomicLevel `json:"level" yaml:"level"`// Development puts the logger in development mode, which changes the// behavior of DPanicLevel and takes stacktraces more liberally.Development bool `json:"development" yaml:"development"`// DisableCaller stops annotating logs with the calling function's file// name and line number. By default, all logs are annotated.DisableCaller bool `json:"disableCaller" yaml:"disableCaller"`// DisableStacktrace completely disables automatic stacktrace capturing. By// default, stacktraces are captured for WarnLevel and above logs in// development and ErrorLevel and above in production.DisableStacktrace bool `json:"disableStacktrace" yaml:"disableStacktrace"`// Sampling sets a sampling policy. A nil SamplingConfig disables sampling.Sampling *SamplingConfig `json:"sampling" yaml:"sampling"`// Encoding sets the logger's encoding. Valid values are "json" and// "console", as well as any third-party encodings registered via// RegisterEncoder.Encoding string `json:"encoding" yaml:"encoding"`// EncoderConfig sets options for the chosen encoder. See// zapcore.EncoderConfig for details.EncoderConfig zapcore.EncoderConfig `json:"encoderConfig" yaml:"encoderConfig"`// OutputPaths is a list of URLs or file paths to write logging output to.// See Open for details.OutputPaths []string `json:"outputPaths" yaml:"outputPaths"`// ErrorOutputPaths is a list of URLs to write internal logger errors to.// The default is standard error.//// Note that this setting only affects internal errors; for sample code that// sends error-level logs to a different location from info- and debug-level// logs, see the package-level AdvancedConfiguration example.ErrorOutputPaths []string `json:"errorOutputPaths" yaml:"errorOutputPaths"`// InitialFields is a collection of fields to add to the root logger.InitialFields map[string]interface{} `json:"initialFields" yaml:"initialFields"`
}

logger 实例创建的源码分析

func NewDevelopment(options ...Option) (*Logger, error) {return  NewDevelopmentConfig().Build(options...)
}func NewDevelopmentConfig() Config {return Config{Level:            NewAtomicLevelAt(DebugLevel),Development:      true,Encoding:         "console",EncoderConfig:    NewDevelopmentEncoderConfig(),OutputPaths:      []string{"stderr"},ErrorOutputPaths: []string{"stderr"},}
}//config的build方法
func (cfg Config) Build(opts ...Option) (*Logger, error) { enc, err := cfg.buildEncoder()if err != nil {return nil, err}sink, errSink, err := cfg.openSinks()if err != nil {return nil, err}if cfg.Level == (AtomicLevel{}) {return nil, fmt.Errorf("missing Level")}//关键之方法new()以及里面的zapcore.NewCore(enc, sink, cfg.Level)方法中的三个参数// enc -> zapcore.Encoder 意思以什么格式写入日志// sink -> zapcore.WriteSyncer  日志写到什么地方 // 日志等级cfg.Level 那种级别的日志将别写入log := New(zapcore.NewCore(enc, sink, cfg.Level),cfg.buildOptions(errSink)...,)if len(opts) > 0 {log = log.WithOptions(opts...)}return log, nil
}

go 日志库zap的使用相关推荐

  1. golang高性能日志库zap的使用

    本文作者:陈进坚 个人博客:https://jian1098.github.io CSDN博客:https://blog.csdn.net/c_jian 简书:https://www.jianshu. ...

  2. 深度|从Go高性能日志库zap看如何实现高性能Go组件

    导语:zap是uber开源的Go高性能日志库.本文作者深入分析了zap的架构设计和具体实现,揭示了zap高效的原因.并且对如何构建高性能Go语言库给出自己的建议. 作者简介:李子昂,美图公司架构平台系 ...

  3. 高性能 Go 日志库 zap 设计与实现

    作者 | luozhiyun       责编 | 欧阳姝黎 最近在学习如何在开发中让代码运行更加高效时,在浏览各种优秀的日志设计的时候看到 uber 有一个叫 zap 的日志库引起了我的注意,它主要 ...

  4. Golang高性能日志库zap + lumberjack 日志切割组件详解

    文章篇幅较长,可以先收藏防止迷路~ 目录 zap日志库 1. why zap? 2. 简单使用 3. 自定义logger例子 4. Gin项目使用zap 6. lumberjack 日志切割组件 za ...

  5. 深度 | 从Go高性能日志库zap看如何实现高性能Go组件

    导语:zap是uber开源的Go高性能日志库.本文作者深入分析了zap的架构设计和具体实现,揭示了zap高效的原因.并且对如何构建高性能Go语言库给出自己的建议. 作者简介:李子昂,美图公司架构平台系 ...

  6. Golang一日一库之 日志库 zap

    简介 在开发过程中 会使用到日志库去记录错误的日志,尤其是golang中 有无穷无尽的error 如果不记录,当你的代码出错,就无从排错了. zap 是开源的 Go 高性能日志库 主要有以下特点: 支 ...

  7. Golang日志库Zap基本使用

    Zap Uber-go Zap简介 Zap Logger Logger Sugared Logger 配置Logger New函数详情 JSON Encoder Log Encoder 更改时间编码 ...

  8. go 日志库 zap

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言 一.zap是什么? 二.使用步骤 1.基本使用 2.写入文件 前言 zap日志 Zap提供了两种类型的日志记录器-Su ...

  9. go第三方日志库 Zap

    //官方文档 //https://pkg.go.dev/go.uber.org/zap#section-readmepackage mainimport ("encoding/json&qu ...

最新文章

  1. Redis进阶-如何发现和优雅的处理BigKey一二事
  2. 基于Axure的火车购票APP
  3. Oracle 12C CDB、PDB常用管理命令
  4. Qt文档阅读笔记-QGraphicsItem events解析与实例
  5. lasso模型交替方向matlab_TCGA系列学习笔记(7)建模及模型评价
  6. PyCharm编辑器的安装
  7. 为什么 Python 4.0 会与 Python 3.0 不同?
  8. *** cannot be resolved or is not a field
  9. VMware Workstation无法提供该虚拟机所需的所有图形功能
  10. AI界的革命!终于可以自动标注了!
  11. html中多个网页的跳转页面,Html --- Footer 多页面应用跳转
  12. C内存分配方式与C++内存分配方式
  13. 什么是 JScript?
  14. 《Windows游戏编程大师技巧》(第二版)第1章(下)
  15. 403错误(已解决)
  16. 软件设计师知识点(七):程序设计语言与语言处理程序、法律法规知识
  17. window.scrollTo控制滚动条平滑的滚动到某个位置
  18. 辉芒微MCU全系列供应,FT60,61,62
  19. UG导出CAD图纸的方法
  20. 非科班程序员被裁员后反而涨薪了200%,这两个月他都经历了哪些?

热门文章

  1. 保姆式教学:用Tableau制作盒须图(箱线图)
  2. MyEclipse使用教程:unattended安装
  3. Python图片处理模块PIL操作方法(pillow)(转载)
  4. 创客平台靠什么盈利?
  5. 华为交换机运行过多设备会导致内存不足解决方法
  6. 「自控原理」3.3 稳定性与稳态误差、时域校正
  7. 线性插值(双线性)(三线性)
  8. windows10在哪修改内网网段或者固定IP
  9. B站品牌UP主内容营销,企业和UP主如何双赢?
  10. 去哪儿2018春季校园招聘软件开发工程师笔试经验