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?

logging formatterのタイムスタンプの桁数を増やしたい。

Posted at

背景

loggingを使って出力するログのフォーマットをいじる機会があり、タイムスタンプの桁数について調べ直したことを残しておきます。

ログのフォーマットをいじる時に調べたものもまとめるつもりでしたが、一つの記事に入れるとわかりにくいのでそっちは別の記事で。

結論

サンプルコードはこちらです。
default_time_formatとdefault_msec_formatを定義してあげることで設定可能です。

フォーマットの変更については上記の通り別の記事ですがコードは新しいサンプル作るのめんどかったのでこれで。。
json形式で作成した構造化ログです。

class CustomFormatter(Formatter):

    default_time_format = '%Y-%m-%d %H:%M:%S'
    default_msec_format = '%s.%06d'

    # この下で使いたいログのフォーマットを指定
    def format(self, record: LogRecord) -> str:

        log_data = {
            "timestamp": self.formatTime(record), 
            "level": record.levelname,
            "message": message,
            # その他加えたいフォーマット
        }
        return json.dumps(log_data)

桁数の追加について

みたまんまですが、default_msec_formatに桁数を指定することができます。
上の例だとログは

{"timestamp": "2025-03-25 10:00:00,123456", "level": "INFO", "messages": "sample message."}

という感じになります。
3桁の場合は下のようにしてあげればOK。

default_msec_format = '%s.%03d'

参考文献

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?