[Python] Dynamic filename with TimedRotatingFileHandler

Discussão em 'Python' iniciado por Stack, Março 11, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página