GoFrame 框架:日誌配置管理

語言: CN / TW / HK

介紹

通過一個完整例子,在 gogf/gf 框架中合理管理日誌。

有什麼使用場景?

  • 日誌自動滾動
  • 分成多個日誌檔案
  • 日誌格式修改
  • 等等

我們將會使用 rk-boot 來啟動 gogf/gf 框架的微服務。

請訪問如下地址獲取完整教程:

安裝

go get github.com/rookie-ninja/rk-boot/gf

簡述概念

rk-boot 使用如下兩個庫管理日誌。

rk-boot 定義了兩種日誌型別,會在後面詳細介紹,這裡先做個簡短介紹。

  • ZapLogger: 標準日誌,用於記錄 Error, Info 等。
  • EventLogger: JSON 或者 Console 格式,用於記錄 Event,例如 RPC 請求。

快速開始

在這個例子中,我們會試著改變 zap 日誌的路徑和格式。

1.建立 boot.yaml

---
zapLogger:
  - name: zap-log                        # Required
    zap:
      encoding: json                     # Optional, options: console, json
      outputPaths: ["logs/zap.log"]      # Optional
gf:
  - name: greeter
    port: 8080
    enabled: true

2.建立 main.go

往 zap-log 日誌例項中寫個日誌。

// Copyright (c) 2021 rookie-ninja
//
// Use of this source code is governed by an Apache-style
// license that can be found in the LICENSE file.

package main

import (
	"context"
	"github.com/rookie-ninja/rk-boot"
	_ "github.com/rookie-ninja/rk-boot/gf"
)

func main() {
	// Create a new boot instance.
	boot := rkboot.NewBoot()

	// Bootstrap
	boot.Bootstrap(context.Background())

	// Write zap log
	boot.GetZapLoggerEntry("zap-log").GetLogger().Info("This is zap-log")

	// Wait for shutdown sig
	boot.WaitForShutdownSig(context.Background())
}

3.驗證

資料夾結構

├── boot.yaml
├── go.mod
├── go.sum
├── logs
│   └── zap.log
└── main.go

日誌輸出

{"level":"INFO","ts":"2021-10-21T02:10:09.279+0800","msg":"This is zap-log"}

配置 EventLogger

上面的例子中,我們配置了 zap 日誌,這回我們修改一下 EventLogger。

1.建立 boot.yaml

---
eventLogger:
  - name: event-log                      # Required
    encoding: json                       # Optional, options: console, json
    outputPaths: ["logs/event.log"]      # Optional
gf:
  - name: greeter
    port: 8080
    enabled: true

2.建立 main.go

往 event-log 例項中寫入日誌。

package main

import (
	"context"
	"github.com/rookie-ninja/rk-boot"
	"github.com/rookie-ninja/rk-entry/entry"
)

func main() {
	// Create a new boot instance.
	boot := rkboot.NewBoot()

	// Bootstrap
	boot.Bootstrap(context.Background())

	// Write event log
	helper := boot.GetEventLoggerEntry("event-log").GetEventHelper()
	event := helper.Start("demo-event")
	event.AddPair("key", "value")
	helper.Finish(event)

	// Wait for shutdown sig
	boot.WaitForShutdownSig(context.Background())
}

3.啟動 main.go

$ go run main.go

4.驗證

資料夾結構

├── boot.yaml
├── go.mod
├── go.sum
├── logs
│   └── event.log
└── main.go

日誌內容

{"endTime": "2022-01-18T22:18:44.926+0800", "startTime": "2022-01-18T22:18:44.926+0800", "elapsedNano": 746, "timezone": "CST", "ids": {"eventId":"2aaea6f5-c7ac-4245-ac50-857726f3ede4"}, "app": {"appName":"rk","appVersion":"","entryName":"","entryType":""}, "env": {"arch":"amd64","az":"*","domain":"*","hostname":"lark.local","localIP":"10.8.0.2","os":"darwin","realm":"*","region":"*"}, "payloads": {}, "error": {}, "counters": {}, "pairs": {"key":"value"}, "timing": {}, "remoteAddr": "localhost", "operation": "demo-event", "eventStatus": "Ended", "resCode": "OK"}

概念

上面的例子中,我們嘗試了 ZapLogger 和 EventLogger。接下來我們看看 rk-boot 是如何實現的,並且怎麼使用。

架構

ZapLoggerEntry

ZapLoggerEntry 是 zap 例項的一個封裝。

// ZapLoggerEntry contains bellow fields.
// 1: EntryName: Name of entry.
// 2: EntryType: Type of entry which is ZapLoggerEntryType.
// 3: EntryDescription: Description of ZapLoggerEntry.
// 4: Logger: zap.Logger which was initialized at the beginning.
// 5: LoggerConfig: zap.Logger config which was initialized at the beginning which is not accessible after initialization..
// 6: LumberjackConfig: lumberjack.Logger which was initialized at the beginning.
type ZapLoggerEntry struct {
	EntryName        string             `yaml:"entryName" json:"entryName"`
	EntryType        string             `yaml:"entryType" json:"entryType"`
	EntryDescription string             `yaml:"entryDescription" json:"entryDescription"`
	Logger           *zap.Logger        `yaml:"-" json:"-"`
	LoggerConfig     *zap.Config        `yaml:"zapConfig" json:"zapConfig"`
	LumberjackConfig *lumberjack.Logger `yaml:"lumberjackConfig" json:"lumberjackConfig"`
}

如何在 boot.yaml 裡配置 ZapLoggerEntry?

ZapLoggerEntry 完全相容 zaplumberjack 的 YAML 結構。 使用者可以根據需求,配置多個 ZapLogger 例項,並且通過 name 來訪問。

完整配置:

---
zapLogger:
  - name: zap-logger                      # Required
    description: "Description of entry"   # Optional
    zap:
      level: info                         # Optional, default: info, options: [debug, DEBUG, info, INFO, warn, WARN, dpanic, DPANIC, panic, PANIC, fatal, FATAL]
      development: true                   # Optional, default: true
      disableCaller: false                # Optional, default: false
      disableStacktrace: true             # Optional, default: true
      sampling:                           # Optional, default: empty map
        initial: 0
        thereafter: 0
      encoding: console                   # Optional, default: "console", options: [console, json]
      encoderConfig:
        messageKey: "msg"                 # Optional, default: "msg"
        levelKey: "level"                 # Optional, default: "level"
        timeKey: "ts"                     # Optional, default: "ts"
        nameKey: "logger"                 # Optional, default: "logger"
        callerKey: "caller"               # Optional, default: "caller"
        functionKey: ""                   # Optional, default: ""
        stacktraceKey: "stacktrace"       # Optional, default: "stacktrace"
        lineEnding: "\n"                  # Optional, default: "\n"
        levelEncoder: "capitalColor"      # Optional, default: "capitalColor", options: [capital, capitalColor, color, lowercase]
        timeEncoder: "iso8601"            # Optional, default: "iso8601", options: [rfc3339nano, RFC3339Nano, rfc3339, RFC3339, iso8601, ISO8601, millis, nanos]
        durationEncoder: "string"         # Optional, default: "string", options: [string, nanos, ms]
        callerEncoder: ""                 # Optional, default: ""
        nameEncoder: ""                   # Optional, default: ""
        consoleSeparator: ""              # Optional, default: ""
      outputPaths: [ "stdout" ]           # Optional, default: ["stdout"], stdout would be replaced if specified
      errorOutputPaths: [ "stderr" ]      # Optional, default: ["stderr"], stderr would be replaced if specified
      initialFields:                      # Optional, default: empty map
        key: "value"
    lumberjack:                           # Optional
      filename: "rkapp-event.log"         # Optional, default: It uses <processname>-lumberjack.log in os.TempDir() if empty.
      maxsize: 1024                       # Optional, default: 1024 (MB)
      maxage: 7                           # Optional, default: 7 (days)
      maxbackups: 3                       # Optional, default: 3 (days)
      localtime: true                     # Optional, default: true
      compress: true                      # Optional, default: true

如何在程式碼裡獲取 ZapLogger?

通過 name 來訪問。

boot := rkboot.NewBoot()

// Access entry
boot.GetZapLoggerEntry("zap-logger")

// Access zap logger
boot.GetZapLoggerEntry("zap-logger").GetLogger()

// Access zap logger config
boot.GetZapLoggerEntry("zap-logger").GetLoggerConfig()

// Access lumberjack config
boot.GetZapLoggerEntry("zap-logger").GetLumberjackConfig()

EventLoggerEntry

rk-boot 把每一個 RPC 請求看作一個 Event,並且使用 rk-query 中的 Event 型別來記錄日誌。

// EventLoggerEntry contains bellow fields.
// 1: EntryName: Name of entry.
// 2: EntryType: Type of entry which is EventLoggerEntryType.
// 3: EntryDescription: Description of EventLoggerEntry.
// 4: EventFactory: rkquery.EventFactory was initialized at the beginning.
// 5: EventHelper: rkquery.EventHelper was initialized at the beginning.
// 6: LoggerConfig: zap.Config which was initialized at the beginning which is not accessible after initialization.
// 7: LumberjackConfig: lumberjack.Logger which was initialized at the beginning.
type EventLoggerEntry struct {
	EntryName        string                `yaml:"entryName" json:"entryName"`
	EntryType        string                `yaml:"entryType" json:"entryType"`
	EntryDescription string                `yaml:"entryDescription" json:"entryDescription"`
	EventFactory     *rkquery.EventFactory `yaml:"-" json:"-"`
	EventHelper      *rkquery.EventHelper  `yaml:"-" json:"-"`
	LoggerConfig     *zap.Config           `yaml:"zapConfig" json:"zapConfig"`
	LumberjackConfig *lumberjack.Logger    `yaml:"lumberjackConfig" json:"lumberjackConfig"`
}

EventLogger 欄位

我們可以看到 EventLogger 打印出來的日誌裡,包含欄位,介紹一下這些欄位。

欄位 詳情
endTime 結束時間
startTime 開始時間
elapsedNano Event 時間開銷(Nanoseconds)
timezone 時區
ids 包含 eventId, requestId 和 traceId。如果原資料攔截器被啟動,或者 event.SetRequest() 被使用者呼叫,新的 RequestId 將會被使用,同時 eventId 與 requestId 會一模一樣。 如果呼叫鏈攔截器被啟動,traceId 將會被記錄。
app 包含 appName, appVersion, entryName, entryType。
env 包含 arch, az, domain, hostname, localIP, os, realm, region. realm, region, az, domain 欄位。這些欄位來自系統環境變數(REALM,REGION,AZ,DOMAIN)。 "*" 代表環境變數為空。
payloads 包含 RPC 相關資訊。
error 包含錯誤。
counters 通過 event.SetCounter() 來操作。
pairs 通過 event.AddPair() 來操作。
timing 通過 event.StartTimer() 和 event.EndTimer() 來操作。
remoteAddr RPC 遠端地址。
operation RPC 名字。
resCode RPC 返回碼。
eventStatus Ended 或者 InProgress

例子

------------------------------------------------------------------------
endTime=2021-11-27T02:30:27.670807+08:00
startTime=2021-11-27T02:30:27.670745+08:00
elapsedNano=62536
timezone=CST
ids={"eventId":"4bd9e16b-2b29-4773-8908-66c860bf6754"}
app={"appName":"gf-demo","appVersion":"master-f948c90","entryName":"greeter","entryType":"GfEntry"}
env={"arch":"amd64","az":"*","domain":"*","hostname":"lark.local","localIP":"10.8.0.6","os":"darwin","realm":"*","region":"*"}
payloads={"apiMethod":"GET","apiPath":"/rk/v1/healthy","apiProtocol":"HTTP/1.1","apiQuery":"","userAgent":"curl/7.64.1"}
error={}
counters={}
pairs={}
timing={}
remoteAddr=localhost:61726
operation=/rk/v1/healthy
resCode=200
eventStatus=Ended
EOE

如何在 boot.yaml 裡配置 EventLoggerEntry?

EventLoggerEntry 將會把 Application 名字注入到 Event 中。啟動器會從 go.mod 檔案中提取 Application 名字。 如果沒有 go.mod 檔案,啟動器會使用預設的名字。

使用者可以根據需求,配置多個 EventLogger 例項,並且通過 name 來訪問。

完整配置:

---
eventLogger:
  - name: event-logger                 # Required
    description: "This is description" # Optional
    encoding: console                  # Optional, default: console, options: console and json
    outputPaths: ["stdout"]            # Optional
    lumberjack:                        # Optional
      filename: "rkapp-event.log"      # Optional, default: It uses <processname>-lumberjack.log in os.TempDir() if empty.
      maxsize: 1024                    # Optional, default: 1024 (MB)
      maxage: 7                        # Optional, default: 7 (days)
      maxbackups: 3                    # Optional, default: 3 (days)
      localtime: true                  # Optional, default: true
      compress: true                   # Optional, default: true

如何在程式碼裡獲取 EventLogger?

通過 name 來訪問。

boot := rkboot.NewBoot()

// Access entry
boot.GetEventLoggerEntry("event-logger")

// Access event factory
boot.GetEventLoggerEntry("event-logger").GetEventFactory()

// Access event helper
boot.GetEventLoggerEntry("event-logger").GetEventHelper()

// Access lumberjack config
boot.GetEventLoggerEntry("event-logger").GetLumberjackConfig()

如何使用 Event?

Event 是一個 interface,包含了若干方法,請參考:Event

常用方法:

boot := rkboot.NewBoot()

// Get EventHelper to create Event instance
helper := boot.GetEventLoggerEntry("event-log").GetEventHelper()

// Start and finish event
event := helper.Start("demo-event")
helper.Finish(event)

// Add K/V
event.AddPair("key", "value")

// Start and end timer
event.StartTimer("my-timer")
event.EndTimer("my-timer")

// Set counter
event.SetCounter("my-counter", 1)