python - Dynamic filename with TimedRotatingFileHandler - Stack Overflow

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

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')

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744789679a4593836.html

相关推荐

  • python - Dynamic filename with TimedRotatingFileHandler - Stack Overflow

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

    10小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信