1
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.

TimedRotatingFileHandlerを使ってログローテーション時にファイルを圧縮する

Last updated at Posted at 2023-05-24

概要

タイトル通り、ログローテーション時にファイルを圧縮する方法の備忘録です😁

ソースコード

custom_logger.py
import os
import gzip
import shutil
from logging import getLogger, Formatter, StreamHandler, DEBUG, INFO
from logging.handlers import TimedRotatingFileHandler


def namer(name):
    return name + ".gz"


def rotator(source, dest):
    with open(source, 'rb') as f_in:
        with gzip.open(dest, 'wb') as f_out:
            shutil.copyfileobj(f_in, f_out)
    os.remove(source)


def setup_logger(name, filename: str, when='MIDNIGHT', backupCount=30):
    # create formatter
    formatter = Formatter('%(asctime)s - %(levelname)s - %(filename)s(%(lineno)d) - %(funcName)s - %(message)s')

    # create a file handler
    file_handler = TimedRotatingFileHandler(filename=filename, encoding='UTF-8', when=when, backupCount=backupCount)
    file_handler.setLevel(INFO)
    file_handler.setFormatter(formatter)
    file_handler.rotator = rotator
    file_handler.namer = namer

    # create a logger
    logger = getLogger(name)
    logger.setLevel(DEBUG)
    logger.addHandler(file_handler)

    return logger

使い方

下記の使い方の場合、
TimedRotatingFileHandlerの引数のwhenに「S」を設定しているので
秒単位でログがローテーションされgz形式に圧縮されます

main.py
from custom_logger import setup_logger

logger = setup_logger(name=__name__, filename='root.log', when='S')

logger.debug('debug message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')

結果

スクリーンショット 2023-05-24 213732.png

参考サイト

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