[Python] Is it possible to dynamically specify the log file name in Python?

Discussão em 'Python' iniciado por Stack, Abril 9, 2025.

  1. Stack

    Stack Membro Participativo

    I am attempting to move some of my programs from Perl to Python. Our Perl logging configuration has the following line:

    # perl_log.conf

    log4perl.appender.LOGFILE.filename= sub { return get_perl_log() }


    In each of our Perl scripts, we have this code block:

    # my_perl_script.pl

    my $perl_log = "/path/to/log.log";

    # Instantiating logger object
    sub get_perl_log{
    return $perl_log;
    }


    I was wondering if it's possible to do this in Python. Currently, we have to create .conf files for each Python script, even though the fileHandlers are the same:

    # my_python_script_log.conf

    [formatters]
    keys=simpleFormatter

    [logger_root]
    level=INFO
    handlers=consoleHandler

    [logger_my_python_script]
    level=DEBUG
    handlers=consoleHandler,fileHandler
    qualname=my_python_script
    propagate=0

    [handler_consoleHandler]
    class=StreamHandler
    level=INFO
    formatter=simpleFormatter
    args=(sys.stdout,)

    [handler_fileHandler]
    class=logging.handlers.TimedRotatingFileHandler
    level=DEBUG
    formatter=simpleFormatter
    args=('/path/to/log/my_python_script.log','midnight',)

    [formatter_simpleFormatter]
    format=%(asctime)s - %(name)s - %(levelname)s - %(message)s



    I'd like to make this Python logging configuration accept a dynamic file name like:

    args=(get_python_log())


    Is this possible?

    Continue reading...

Compartilhe esta Página