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

【Golang】gRPCでzapの設定をしてみる

Last updated at Posted at 2025-03-07

Zapとは?

構造化メッセージを自由に構築できる、高速なロギングライブラリ
gRPCにloggerをセットする用の関数とかも用意されています。

基本的な使い方

loggerを生成して、logを出力する

logger, _ := zap.NewProduction()
logger.Info("test")

interceptorを用いてgRPCにLoggerを設定するには?

gRPCのサーバを作成する際のオプションとして、interceptor(middleware的なもの)を使用すれば、hundlerの前後に任意の処理を挟むことができます。
grpc_zapというzapのloggerをgRPCにセットする用のパッケージも用意されているのでそれを使用するだけで、loggerを設定できます。

server := grpc.NewServer(
    grpc.UnaryInterceptor(grpc_zap.UnaryServerInterceptor(logger)),
)

出力されるログのラベルを変更するには?

configを独自に設定して、それをもとにloggerをBuildしてやればいい。

myConfig := zapcore.EncoderConfig{
    TimeKey:        "xxxx",
    LevelKey:       "xxxx",
    NameKey:        "xxxx",
    CallerKey:      "xxxx",
    MessageKey:     "xxxx",
    StacktraceKey:  "xxxx",
    EncodeLevel:    xxxx,
    EncodeTime:     xxxx,
    EncodeDuration: xxxx,
    EncodeCaller:   xxxx,
}
 
logger, err :=  myConfig.Build()

ログのrotateを設定するには?

zapCoreを生成する際にrotateの設定が可能

Filename : ログの吐き出し場所
MaxSize : ログの最大サイズ(MB)。デフォルトは100MB
MaxBackups : 残しておくログファイル数
MaxAge : 残しておくログファイルの日数
Compress : rotateするときに圧縮するかどうか

writeSyncer := zapcore.AddSync(&lumberjack.Logger{
    Filename:   /test.log,
    MaxSize:    100,
    MaxBackups: 5,
    MaxAge:     30,
    Compress:   true,
})
core := zapcore.NewCore(encoder, zapcore.NewMultiWriteSyncer(infoFileWriteSyncer), debug)
logger := zap.New(core)

ログレベルによって出力先を出し分けするには?

zapCoreを出力先分作成すればよい
ConfigのOutputPathsとErrorOutputPathsはレベルごとに出力先を決めるためのもの、
ではないので注意。紛らわしい

// ログレベルが低い設定を作成。今回はdebug-infoまでを設定
low := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
    return lev >= zap.DebugLevel && lev <= zap.InfoLevel
}) 
 
// ログレベルが高い設定を作成。今回はwarn以上を設定
high := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
    return lev >= zap.WarnLevel
})
 
// それぞれのzapCoreを作成する
lowCore := zapcore.NewCore(Encoder, WriteSyncer,  low)
highCore := zapcore.NewCore(Encoder, WriteSyncer,  high)
 
// coreの配列を作成する
var coreArr []zapcore.Core
coreArr = append(coreArr, lowCore)
coreArr = append(coreArr, highCore)
 
// loggerを作る
logger := zap.New(zapcore.NewTee(coreArr...)
0
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
0
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?