技術系TIPS
PR

logbackのLoggingEventCompositeJsonEncoderのタイムスタンプフォーマット

saratogax
記事内に商品プロモーションを含む場合があります

SpringBoot3 系に伴い、logstashLogbackEncoder のライブラリも 8.0 系にバージョンアップ。

その際、ログに出力されるタイムスタンプのフォーマットが変わってしまいました。

今回は LoggingEventCompositeJsonEncoder のタイムスタンプフォーマットを明示的に指定する方法を紹介します。

タイムスタンプの出力結果

これまでは、タイムスタンプはデフォルト設定にしていましたが、以下のようなフォーマットで出力されていました。

2025-02-19T17:00:00.999+09:00

しかし、ミリ秒の部分がマイクロ秒なのかナノ秒なのか、桁数が大幅に増えてしまったのが今回の問題です。

2025-02-19T17:00:00.999999999+09:00

logbackの設定

logstash-logback-encoder の Customizing Timestamp の説明を見ると、DateTimeFormatter との兼ね合いがあるようです。

Java の DateTimeFormatter についても確認してみましょうか。

なるほど、Z の数によってフォーマットに違いが出てくるのですね。

Offset Z: This formats the offset based on the number of pattern letters. One, two or three letters outputs the hour and minute, without a colon, such as ‘+0130’. The output will be ‘+0000’ when the offset is zero. Four letters outputs the full form of localized offset, equivalent to four letters of Offset-O. The output will be the corresponding localized offset text if the offset is zero. Five letters outputs the hour, minute, with optional second if non-zero, with colon. It outputs ‘Z’ if the offset is zero. Six or more letters throws IllegalArgumentException.

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html

ということで、これまでと同じフォーマットにする場合は ZZZZZ とすれば良さそうですね。

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
            <providers>
                <timestamp>
                    <pattern>yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ</pattern>
                </timestamp>

                (省略)

            </providers>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="CONSOLE"/>
    </root>
</configuration>
ABOUT ME
saratoga
saratoga
フリーランスエンジニア
仕事にも趣味にも IT を駆使するフリーランスエンジニア。技術的な TIPS や日々の生活の中で深堀りしてみたくなったことを備忘録として残していきます。
記事URLをコピーしました