8
1

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 1 year has passed since last update.

MicroAd (マイクロアド) Advent Calendar 2022

Day 19

zapとzerologをlumberjackと組み合わせてログローテーションする

Last updated at Posted at 2022-12-18

はじめに

今回の記事では、高速なロギングライブラリであるzap、zerologと豊富なログローテーション機能を持つlumberjackライブラリを組み合わせる方法を紹介しようと思います。

lumberjackの設定項目

lumberjackでは以下の項目でログローテーションを制御できます。

  • ログファイルのパス
  • ローテーションサイズ(メガバイト単位)
  • 最長保持期間(日単位)
  • 最大保持数
  • ログの日時情報にローカル時刻を利用するかUTCを利用するか
  • ローテーション後にgzipで圧縮するか

type Logger struct {
	// Filename is the file to write logs to.  Backup log files will be retained
	// in the same directory.  It uses <processname>-lumberjack.log in
	// os.TempDir() if empty.
	Filename string `json:"filename" yaml:"filename"`

	// MaxSize is the maximum size in megabytes of the log file before it gets
	// rotated. It defaults to 100 megabytes.
	MaxSize int `json:"maxsize" yaml:"maxsize"`

	// MaxAge is the maximum number of days to retain old log files based on the
	// timestamp encoded in their filename.  Note that a day is defined as 24
	// hours and may not exactly correspond to calendar days due to daylight
	// savings, leap seconds, etc. The default is not to remove old log files
	// based on age.
	MaxAge int `json:"maxage" yaml:"maxage"`

	// MaxBackups is the maximum number of old log files to retain.  The default
	// is to retain all old log files (though MaxAge may still cause them to get
	// deleted.)
	MaxBackups int `json:"maxbackups" yaml:"maxbackups"`

	// LocalTime determines if the time used for formatting the timestamps in
	// backup files is the computer's local time.  The default is to use UTC
	// time.
	LocalTime bool `json:"localtime" yaml:"localtime"`

	// Compress determines if the rotated log files should be compressed
	// using gzip. The default is not to perform compression.
	Compress bool `json:"compress" yaml:"compress"`
	// contains filtered or unexported fields
}

zap ✖️ lumberjack

zapとlumberjackを連携させるには、zapcore.WriteSyncerを利用します。

package main

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

func main() {
	sink := zapcore.AddSync(&lumberjack.Logger{
		Filename:   "logs/zap.log",
		MaxSize:    10,
		MaxBackups: 10,
		MaxAge:     10,
		Compress:   true,
	})
	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
		sink,
		zap.InfoLevel,
	)
	logger := zap.New(core)
	logger.Info("hoge")
}

出力されるログファイルは以下になります。

{"level":"info","ts":1671340569.6598823,"msg":"hoge"}

zerolog ✖️ lumberjack

zapの場合はLogger生成時にlumberjackで作成したWriterを渡すだけなのでかなりシンプルです。

package main

import (
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"gopkg.in/natefinch/lumberjack.v2"
)

func main() {
	writer := &lumberjack.Logger{
		Filename:   "logs/zerolog.log",
		MaxSize:    10,
		MaxBackups: 10,
		MaxAge:     10,
		Compress:   true,
	}

	log.Logger = zerolog.New(writer).With().Timestamp().Logger()
	log.Info().Msg("hoge")
}

出力されるログファイルは以下になります。

{"level":"info","time":"2022-12-18T05:17:56Z","message":"hoge"}
8
1
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
8
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?