Go 語言之自定義 zap 日誌

来源:https://www.cnblogs.com/QiaoPengjun/archive/2023/06/17/17487453.html
-Advertisement-
Play Games

# Go 語言之自定義 zap 日誌 [zap 日誌](https://github.com/uber-go/zap):https://github.com/uber-go/zap ## 一、日誌寫入文件 - `zap.NewProduction`、`zap.NewDevelopment` 是預設配 ...


Go 語言之自定義 zap 日誌

zap 日誌https://github.com/uber-go/zap

一、日誌寫入文件

  • zap.NewProductionzap.NewDevelopment 是預設配置好的。
  • zap.New 可自定義配置

zap.New源碼

這是構造Logger最靈活的方式,但也是最冗長的方式。

對於典型的用例,高度固執己見的預設(NewProduction、NewDevelopment和NewExample)或Config結構體更方便。

// New constructs a new Logger from the provided zapcore.Core and Options. If
// the passed zapcore.Core is nil, it falls back to using a no-op
// implementation.
//
// This is the most flexible way to construct a Logger, but also the most
// verbose. For typical use cases, the highly-opinionated presets
// (NewProduction, NewDevelopment, and NewExample) or the Config struct are
// more convenient.
//
// For sample code, see the package-level AdvancedConfiguration example.
func New(core zapcore.Core, options ...Option) *Logger {
	if core == nil {
		return NewNop()
	}
	log := &Logger{
		core:        core,
		errorOutput: zapcore.Lock(os.Stderr),
		addStack:    zapcore.FatalLevel + 1,
		clock:       zapcore.DefaultClock,
	}
	return log.WithOptions(options...)
}

zapcore.Core 源碼

// Core is a minimal, fast logger interface. It's designed for library authors
// to wrap in a more user-friendly API.
type Core interface {
	LevelEnabler

	// With adds structured context to the Core.
	With([]Field) Core
	// Check determines whether the supplied Entry should be logged (using the
	// embedded LevelEnabler and possibly some extra logic). If the entry
	// should be logged, the Core adds itself to the CheckedEntry and returns
	// the result.
	//
	// Callers must use Check before calling Write.
	Check(Entry, *CheckedEntry) *CheckedEntry
	// Write serializes the Entry and any Fields supplied at the log site and
	// writes them to their destination.
	//
	// If called, Write should always log the Entry and Fields; it should not
	// replicate the logic of Check.
	Write(Entry, []Field) error
	// Sync flushes buffered logs (if any).
	Sync() error
}

zapcore.AddSync(file) 源碼解析

func AddSync(w io.Writer) WriteSyncer {
	switch w := w.(type) {
	case WriteSyncer:
		return w
	default:
		return writerWrapper{w}
	}
}

type writerWrapper struct {
	io.Writer
}

func (w writerWrapper) Sync() error {
	return nil
}

type WriteSyncer interface {
	io.Writer
	Sync() error
}

日誌級別

// A Level is a logging priority. Higher levels are more important.
type Level int8

const (
	// DebugLevel logs are typically voluminous, and are usually disabled in
	// production.
	DebugLevel Level = iota - 1
	// InfoLevel is the default logging priority.
	InfoLevel
	// WarnLevel logs are more important than Info, but don't need individual
	// human review.
	WarnLevel
	// ErrorLevel logs are high-priority. If an application is running smoothly,
	// it shouldn't generate any error-level logs.
	ErrorLevel
	// DPanicLevel logs are particularly important errors. In development the
	// logger panics after writing the message.
	DPanicLevel
	// PanicLevel logs a message, then panics.
	PanicLevel
	// FatalLevel logs a message, then calls os.Exit(1).
	FatalLevel

	_minLevel = DebugLevel
	_maxLevel = FatalLevel

	// InvalidLevel is an invalid value for Level.
	//
	// Core implementations may panic if they see messages of this level.
	InvalidLevel = _maxLevel + 1
)

實操

package main

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

// 定義一個全局 logger 實例
// Logger提供快速、分級、結構化的日誌記錄。所有方法對於併發使用都是安全的。
// Logger是為每一微秒和每一個分配都很重要的上下文設計的,
// 因此它的API有意傾向於性能和類型安全,而不是簡便性。
// 對於大多數應用程式,SugaredLogger在性能和人體工程學之間取得了更好的平衡。
var logger *zap.Logger

// SugaredLogger將基本的Logger功能封裝在一個較慢但不那麼冗長的API中。任何Logger都可以通過其Sugar方法轉換為sugardlogger。
//與Logger不同,SugaredLogger並不堅持結構化日誌記錄。對於每個日誌級別,它公開了四個方法:
//   - methods named after the log level for log.Print-style logging
//   - methods ending in "w" for loosely-typed structured logging
//   - methods ending in "f" for log.Printf-style logging
//   - methods ending in "ln" for log.Println-style logging

// For example, the methods for InfoLevel are:
//
//	Info(...any)           Print-style logging
//	Infow(...any)          Structured logging (read as "info with")
//	Infof(string, ...any)  Printf-style logging
//	Infoln(...any)         Println-style logging
var sugarLogger *zap.SugaredLogger

func main() {
	// 初始化
	InitLogger()
	// Sync調用底層Core的Sync方法,刷新所有緩衝的日誌條目。應用程式在退出之前應該註意調用Sync。
	// 在程式退出之前,把緩衝區里的日誌刷到磁碟上
	defer logger.Sync()
	simpleHttpGet("www.baidu.com")
	simpleHttpGet("http://www.baidu.com")
}

func InitLogger() {
	writeSyncer := getLogWriter()
	encoder := getEncoder()
	// NewCore創建一個向WriteSyncer寫入日誌的Core。

	// A WriteSyncer is an io.Writer that can also flush any buffered data. Note
	// that *os.File (and thus, os.Stderr and os.Stdout) implement WriteSyncer.

	// LevelEnabler決定在記錄消息時是否啟用給定的日誌級別。
	// Each concrete Level value implements a static LevelEnabler which returns
	// true for itself and all higher logging levels. For example WarnLevel.Enabled()
	// will return true for WarnLevel, ErrorLevel, DPanicLevel, PanicLevel, and
	// FatalLevel, but return false for InfoLevel and DebugLevel.
	core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)

	// New constructs a new Logger from the provided zapcore.Core and Options. If
	// the passed zapcore.Core is nil, it falls back to using a no-op
	// implementation.
	logger = zap.New(core)
	// Sugar封裝了Logger,以提供更符合人體工程學的API,但速度略慢。糖化一個Logger的成本非常低,
	// 因此一個應用程式同時使用Loggers和SugaredLoggers是合理的,在性能敏感代碼的邊界上在它們之間進行轉換。
	sugarLogger = logger.Sugar()
}

func getEncoder() zapcore.Encoder {
	// NewJSONEncoder創建了一個快速、低分配的JSON編碼器。編碼器適當地轉義所有欄位鍵和值。
	// NewProductionEncoderConfig returns an opinionated EncoderConfig for
	// production environments.
	return zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
}

func getLogWriter() zapcore.WriteSyncer {
	// Create創建或截斷指定文件。如果文件已經存在,它將被截斷。如果該文件不存在,則以模式0666(在umask之前)創建。
	// 如果成功,返回的File上的方法可以用於IO;關聯的文件描述符模式為O_RDWR。如果有一個錯誤,它的類型將是PathError。
	file, _ := os.Create("./test.log")
	// AddSync converts an io.Writer to a WriteSyncer. It attempts to be
	// intelligent: if the concrete type of the io.Writer implements WriteSyncer,
	// we'll use the existing Sync method. If it doesn't, we'll add a no-op Sync.
	return zapcore.AddSync(file)
}

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(

		// 錯誤使用fmt。以Sprint方式構造和記錄消息。
		sugarLogger.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..",

		// Info使用fmt。以Sprint方式構造和記錄消息。
		sugarLogger.Info("Success..",
			zap.String("statusCode", resp.Status),
			zap.String("url", url))
		resp.Body.Close()
	}
}

運行

Code/go/zap_demo via 

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • # Java 註釋、絕對路徑、相對路徑、基本Dos命令 # 1. Java的三種註釋方式 ## 註釋能增加代碼的可讀性,習慣寫註釋能提升我們編寫代碼的能力 > ### 單行註釋:用//註釋一些代碼提示 > > ### 多行註釋:以/*為開頭 以 */為結束 > > ### 文檔註釋:/* > > # ...
  • # 1.Java 發展歷史 ### 由高斯林創建 1995年由甲骨文公司收購併發出第一版本,目前使用最多是Java8 及 Java11 原因是這兩個版本都是長期支持維護的,企業用的也比較多。 # 2.Java的一些特點 > ### 跨平臺性:主要是因為每個平臺都裝有 JVM > ### Java 是 ...
  • #### 1. 跳出/執行下一次迴圈。 ``` {標簽名}: for true { ... for true { ... break/continue {標簽名} //預設不加標簽,則跳出最近一層迴圈。加了標簽可以跳出標簽定義處所在迴圈 } } ``` #### 2. map的使用註意項。 因為ma ...
  • 最近在弄文件上傳、下載、線上預覽時經常需要設置請求標頭或者響應標頭的Content-Type 屬性。所以研究了一下spring支持哪些Content-Type,通過研究MediaTypeFactory.getMediaType的源碼,可以得知spring是將支持的Content-Type 維護在/o... ...
  • # Go 語言之在 gin 框架中使用 zap 日誌庫 ### gin 框架預設使用的是自帶的日誌 #### `gin.Default()`的源碼 Logger(), Recovery() ```go func Default() *Engine { debugPrintWARNINGDefault ...
  • ## 概述 Nginx 是一個高性能的 HTTP 和反向代理伺服器,特點是占用記憶體少,併發能力強 #### 1. 正向代理 如果把區域網外的 Internet 想象成一個巨大的資源庫,則區域網中的客戶端要訪問 Internet,需要通過代理伺服器來訪問,這種訪問就稱為正向代理 ![](https:/ ...
  • # 類和對象 **組成結構** • 構造函數: 在創建對象的時候給屬性賦值 • 成員變數: • 成員方法(函數) • 局部變數 • 代碼塊 ## 構造器 每個類都有一個主構造器,這個構造器和類定義"交織"在一起類名後面的內容就是主構造器,如果參數列表為空的話,()可以省略 scala的類有且僅有一個 ...
  • ## 1.常用命令 `創建項目:django-admin startproject 項目名` `創建APP(進入工程目錄):python manage.py startapp 網站名` `創建庫表(進入工程目錄):python manage.py makemigrations` `執行庫表建立(進入 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...