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?

More than 1 year has passed since last update.

Pythonのloggingでログファイルを年月ごとのディレクトリに出力したい

0
Last updated at Posted at 2025-05-10

やりたいこと

Python標準のloggingの使用して年月ごとのディレクトリにログファイルを出力します。

LOG_DIR
├── 2025
│   ├── 01
│   │   ├── LOG_FILE.20250101.log
│   │   ├── ...
│   │   └── LOG_FILE.20250131.log
│   └── 02
│       ├── LOG_FILE.20250201.log
│       ├── ...
│       └── LOG_FILE.20250228.log
└── LOG_FILE

実装

TimedRotatingFileHandlerを継承します。

サンプルコード
import re
import time
from datetime import datetime
from logging import getLogger
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path


class MyTimedRoatingFileHandler(TimedRotatingFileHandler):
    def __init__(
        self,
        filename,
        when="h",
        interval=1,
        backupCount=0,
        encoding=None,
        delay=False,
        utc=False,
        atTime=None,
        errors=None,
    ):
        super().__init__(
            filename, when, interval, backupCount, encoding, delay, utc, atTime, errors
        )
        # ファイル名の日時フォーマットの「-」と「_」を取り除く
        # e.g. LOG_FILE.2025-01-01_12-30-40 -> LOG_FILE.20250101123040
        self.suffix = re.sub(r"([-_])", "", self.suffix)
        extMatch = re.sub(r"([-_])", "", self.extMatch.pattern)
        self.extMatch = re.compile(extMatch, re.ASCII)

    def rotation_filename(self, default_name):
        # default_nameから日時を取り出す
        dt_str = self.extMatch.findall(default_name)[-1]
        dt = datetime.strptime(dt_str, self.suffix)
        # 年/月ディレクトリを挿入する
        # e.g. LOG_DIR/LOG_FILE -> LOG_DIR/2025/01/LOG_FILE
        default_name_path = Path(default_name)
        default_name = (
            default_name_path.parent
            / dt.strftime("%Y")
            / dt.strftime("%m")
            / default_name_path.name
        )
        return super().rotation_filename(default_name)

    def rotate(self, source, dest):
        # 存在しないディレクトリは作成する
        Path(dest).parent.mkdir(parents=True, exist_ok=True)
        return super().rotate(source, dest)

    def _open(self):
        # 存在しないディレクトリは作成する
        Path(self.baseFilename).parent.mkdir(parents=True, exist_ok=True)
        return super()._open()


# ログを出力してみる
logger = getLogger("logger")
handler = MyTimedRoatingFileHandler("LOG_DIR/LOG_FILE", "S")  # 実運用はwhen="midnight"とします
handler.namer = lambda default_name: f"{default_name}.log"  # 拡張子を.logとします
logger.addHandler(handler)

for i in range(20):
    logger.error(f"ERROR MESSAGE{i}")
    time.sleep(0.5)
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?