LoginSignup
1
0

More than 1 year has passed since last update.

【Go】ロギングライブラリzapの使い方メモ

Posted at

はじめに

Goのロギングライブラリであるzapに関するメモです。

zapとは

構造化メッセージを自由に構築できる、高速なロギングライブラリです。
ベンチマークによると、標準ライブラリ(fmt, encoding/json)やlogrusより高速とのことです。

実装

以下が初期化のプログラムです。

logger.go
package logger

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var log *zap.Logger

func init() {
	var err error

	config := zap.NewProductionConfig()

	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.TimeKey = "timestamp"
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	config.EncoderConfig = encoderConfig

	log, err = config.Build(zap.AddCallerSkip(1))

	if err != nil {
		panic(err)
	}
}

zap.NewProductionConfig()configを定義し、設定を自由にカスタムします。
configの中身は以下のようになっているのですが、今回はEncoderConfigの設定を簡単にいじってみます。

type Config struct {
	Level AtomicLevel `json:"level" yaml:"level"`
	Development bool `json:"development" yaml:"development"`
	DisableCaller bool `json:"disableCaller" yaml:"disableCaller"`
	DisableStacktrace bool `json:"disableStacktrace" yaml:"disableStacktrace"`
	Sampling *SamplingConfig `json:"sampling" yaml:"sampling"`
	Encoding string `json:"encoding" yaml:"encoding"`
	EncoderConfig zapcore.EncoderConfig `json:"encoderConfig" yaml:"encoderConfig"`
	OutputPaths []string `json:"outputPaths" yaml:"outputPaths"`
	ErrorOutputPaths []string `json:"errorOutputPaths" yaml:"errorOutputPaths"`
	InitialFields map[string]interface{} `json:"initialFields" yaml:"initialFields"`
}

zap.NewProductionEncoderConfig()encoderConfigを定義し、ロギング時間のキー名TimeKeyとタイムスタンプEncodeTimeの設定を行います。
そして最後に、config.build(zap.AddCallerSkip(1))でLoggerを生成します。
zap.AddCallerSkip(1)はmLoggerの呼び出し元ファイルの行番号を表示するために必要となります。

またメッセージのレベルごとにfuncを用意してあげます。

logger
func Info(message string, fields ...zap.Field) {
	log.Info(message, fields...)
}

func Debug(message string, fields ...zap.Field) {
	log.Debug(message, fields...)
}

func Error(message string, fields ...zap.Field) {
	log.Error(message, fields...)
}

呼び出し元でloggerを仕込みます。

main.go
package main

import (
	"github.com/suzuki0430/banking-practice/app"
	"github.com/suzuki0430/banking-practice/logger"
)

func main() {
	logger.Info("Starting the application...")
	app.Start()
}

プログラムを実行すると、以下のようなメッセージが表示されます。

{"level":"info","timestamp":"2022-03-25T21:44:40.626+0900","caller":"banking-practice/main.go:11","msg":"Starting the application..."}

参考資料

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0