最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Dynamic filename with TimedRotatingFileHandler - Stack Overflow

programmeradmin1浏览0评论

I would like to store log records for never ending process in log file with date prefix (e.g. 20250311.log).

How could I use a dynamic date for current date file, i.e.

  • f"{dt.datetime.now().strftime('%Y%m%d')}.log"

Currently, I use a static name, e.g. process.log and rename the file at midnight using namer attribute of handler.

import datetime as dt
import logging
from logging.handlers import TimedRotatingFileHandler

logger = logging.getLogger("test")
handler = TimedRotatingFileHandler("process.log", when="midnight")
handler.namer = lambda _: (dt.datetime.now() - dt.timedelta(days=1)).strftime("%Y%m%d_process.log")
logger.addHandler(handler)

Disadvantage is that I need a convention for current date logs - I cannot just open a file with today's date.

I would like to store log records for never ending process in log file with date prefix (e.g. 20250311.log).

How could I use a dynamic date for current date file, i.e.

  • f"{dt.datetime.now().strftime('%Y%m%d')}.log"

Currently, I use a static name, e.g. process.log and rename the file at midnight using namer attribute of handler.

import datetime as dt
import logging
from logging.handlers import TimedRotatingFileHandler

logger = logging.getLogger("test")
handler = TimedRotatingFileHandler("process.log", when="midnight")
handler.namer = lambda _: (dt.datetime.now() - dt.timedelta(days=1)).strftime("%Y%m%d_process.log")
logger.addHandler(handler)

Disadvantage is that I need a convention for current date logs - I cannot just open a file with today's date.

Share Improve this question asked Mar 11 at 14:09 not_real_moderatornot_real_moderator 17 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

I cannot just open a file with today's date.

It is not clear why you "cannot" use f-string and datetime to form a filename

If you want more control or processing logic on the filename, You can create your own custom class by inheriting TimedRotatingFileHandler class.

Before passing the filename to the parent class, you can process it as you wish. It behaves just like TimedRotatingFileHandler class, only difference is whenever new file is created, filename follows your naming convention.

import datetime as dt
import logging
from logging.handlers import TimedRotatingFileHandler


class CustomTimedRotatingFileHandler(TimedRotatingFileHandler):
    """
    Handler for logging to a file, rotating the log file at certain timed
    intervals.

    If backupCount is > 0, when rollover is done, no more than backupCount
    files are kept - the oldest ones are deleted.
    """

    def __init__(
        self,
        filename="",
        when="h",
        interval=1,
        backupCount=0,
        encoding=None,
        delay=False,
        utc=False,
        atTime=None,
        errors=None,
    ):
        if not filename:
            # example 
            filename = (dt.datetime.now() - dt.timedelta(days=1)).strftime(
                "%Y%m%d_process.log"
            )

            # filename = whatever convention you want to use

        TimedRotatingFileHandler.__init__(
            self,
            filename,
            when,
            interval,
            backupCount,
            encoding,
            delay,
            utc,
            atTime,
            errors,
        )


logger = logging.getLogger("test")
handler = CustomTimedRotatingFileHandler("", when="midnight")
logger.addHandler(handler)
logger.warning('this is a warn')
发布评论

评论列表(0)

  1. 暂无评论