Go 语言之 zap 日志库简单使用

默认的 Go log

log:https://pkg.go.dev/log

package main

import (
	"log"
	"os"
)

func init() {
	log.SetPrefix("LOG: ") // 设置前缀

	f, err := os.OpenFile("./log.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		log.Fatalf("open log file failed with error: %v", err)
	}
	log.SetOutput(f) // 设置输出

	log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Llongfile)

	// const (
	// 	Ldate         = 1 << iota // 1 << 0 = 000000001 = 1
	// 	Ltime                     // 1 << 1 = 000000010 = 2
	// 	Lmicroseconds             // 1 << 2 = 000000100 = 4
	// 	Llongfile                 // 1 << 3 = 000001000 = 8
	// 	Lshortfile                // 1 << 4 = 000010000 = 16
	// 	...
	// )
}

func main() {
	log.Println("1234")

	// log.Fatalln("1234")

	// log.Panicln("1234")

	// log.Panic("1234")
	// log.Panicf("1234, %d", 5678)
}

log 包是一个简单的日志包。

Package log implements a simple logging package. It defines a type, Logger, with methods for formatting output. It also has a predefined 'standard' Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and Panic[f|ln], which are easier to use than creating a Logger manually. That logger writes to standard error and prints the date and time of each logged message. Every log message is output on a separate line: if the message being printed does not end in a newline, the logger will add one. The Fatal functions call os.Exit(1) after writing the log message. The Panic functions call panic after writing the log message.

uber-go zap

loghttps://pkg.go.dev/log

github zaphttps://github.com/uber-go/zap

pkg zaphttps://pkg.go.dev/go.uber.org/zap#section-readme

Blazing fast, structured, leveled logging in Go.

安装

go get -u go.uber.org/zap

在性能良好但不是关键的上下文中,使用 SugaredLogger。它比其他结构化日志包快4-10倍,包括结构化和 printf 风格的 API。

logger, _ := zap.NewProduction()
defer logger.Sync() // flushes buffer, if any
sugar := logger.Sugar()
sugar.Infow("failed to fetch URL",
  // Structured context as loosely typed key-value pairs.
  "url", url,
  "attempt", 3,
  "backoff", time.Second,
)
sugar.Infof("Failed to fetch URL: %s", url)

当性能和类型安全至关重要时,请使用Logger。它甚至比SugaredLogger 更快,分配也少得多,但它只支持结构化日志记录。

logger, _ := zap.NewProduction()
defer logger.Sync()
logger.Info("failed to fetch URL",
  // Structured context as strongly typed Field values.
  zap.String("url", url),
  zap.Int("attempt", 3),
  zap.Duration("backoff", time.Second),
)

zap文档https://pkg.go.dev/go.uber.org/zap#section-readme

Logger 简单使用

package main

import (
	"go.uber.org/zap"
	"net/http"
)

// 定义一个全局 logger 实例
// Logger提供快速、分级、结构化的日志记录。所有方法对于并发使用都是安全的。
// Logger是为每一微秒和每一个分配都很重要的上下文设计的,
// 因此它的API有意倾向于性能和类型安全,而不是简便性。
// 对于大多数应用程序,SugaredLogger在性能和人体工程学之间取得了更好的平衡。
var logger *zap.Logger

func main() {
	// 初始化
	InitLogger()
	// Sync调用底层Core的Sync方法,刷新所有缓冲的日志条目。应用程序在退出之前应该注意调用Sync。
	// 在程序退出之前,把缓冲区里的日志刷到磁盘上
	defer logger.Sync()
	simpleHttpGet("www.baidu.com")
	simpleHttpGet("http://www.baidu.com")
}

func InitLogger() {
	// NewProduction构建了一个合理的生产Logger,它将infollevel及以上的日志以JSON的形式写入标准错误。
	// It's a shortcut for NewProductionConfig().Build(...Option).
	logger, _ = zap.NewProduction()
}

func simpleHttpGet(url string) {
	// Get向指定的URL发出Get命令。如果响应是以下重定向代码之一,则Get跟随重定向,最多可重定向10个:
	//	301 (Moved Permanently)
	//	302 (Found)
	//	303 (See Other)
	//	307 (Temporary Redirect)
	//	308 (Permanent Redirect)
	// Get is a wrapper around DefaultClient.Get.
	// 使用NewRequest和DefaultClient.Do来发出带有自定义头的请求。
	resp, err := http.Get(url)
	if err != nil {
		// Error在ErrorLevel记录消息。该消息包括在日志站点传递的任何字段,以及日志记录器上积累的任何字段。
		logger.Error(
			"Error fetching url..",
			zap.String("url", url), // 字符串用给定的键和值构造一个字段。
			zap.Error(err))         // // Error is shorthand for the common idiom NamedError("error", err).
	} else {
		// Info以infollevel记录消息。该消息包括在日志站点传递的任何字段,以及日志记录器上积累的任何字段。
		logger.Info("Success..",
			zap.String("statusCode", resp.Status),
			zap.String("url", url))
		resp.Body.Close()
	}
}

运行

Code/go/zap_demo via 
    

  
内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/QiaoPengjun/p/17487169.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程