2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

logging zap: レベル毎ファイル出力

Last updated at Posted at 2021-06-21

Overview

  • ログレベル毎にファイル出力する要件がまだある。
  • かつ、構造化ログを扱う。
  • zapが柔軟に設定できそうだった。

Detail

設定方法

  • 出力ファイルの作成
  • zap core.EncoderConfigのインスタンス作成
  • zapcore.NewCore(enc Encoder, ws WriteSyncer, enab LevelEnabler) Coreで、レベル別のcoreのインスタンスを作成
  • オプションの生成
  • zap.New(core zapcore.Core, options ...Option) *Logger*Loggerのインスタンスを生成

Sample

InfoErrorを設定。Errorのみ標準エラーとファイルに出力。エラーハンドリングは省略。

package main

import (
	"os"
	"time"

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

func main() {
	infoFile, _ := os.OpenFile("/tmp/info.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	errorFile, _ := os.OpenFile("/tmp/error.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	encoderConfig := zapcore.EncoderConfig{
		TimeKey:        "time",
		LevelKey:       "level",
		NameKey:        "name",
		CallerKey:      "caller",
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     zapcore.ISO8601TimeEncoder,
		EncodeDuration: zapcore.StringDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}

	infoCore := zapcore.NewCore(
		zapcore.NewConsoleEncoder(encoderConfig),
		zapcore.AddSync(infoFile),
		zapcore.InfoLevel,
	)
	sy := zapcore.NewMultiWriteSyncer(os.Stderr, errorFile)
	errorCore := zapcore.NewCore(
		zapcore.NewJSONEncoder(encoderConfig),
		sy,
		zapcore.ErrorLevel,
	)

	opts := []zap.Option{}
	opts = append(opts, zap.WrapCore(func(core zapcore.Core) zapcore.Core {
		return zapcore.NewSampler(
			core,
			time.Second,
			100, //Initial
			100, //Thereafter,
		)
	}))
	logger := zap.New(zapcore.NewTee(infoCore, errorCore), opts...)

	logger.Info("test")
	logger.Error("aaaaaaa")
	//	logger.Fatal("oooooo")
}

Reference

2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?