Format Logfile Name with logging.ini

Peter J. Holzer hjp-python at hjp.at
Fri May 29 16:02:56 EDT 2020


On 2020-05-29 09:52:07 -0700, connor.r.novak at gmail.com wrote:
> In an effort to clean up my python logging practices when creating
> libraries, I have begun reading into "Advanced Logging" and converting
> my logging practices into logging configuration `.ini` files:
> 
> [link](https://docs.python.org/3.4/howto/logging.html#configuring-logging)
> 
> My question is: When defining a FileHandler in a `.ini` file, all of
> the examples that I've seen hardcode the name and location of the log
> file. In the code snippet below, `python.log` is hardcoded into the
> `.ini` file:

This is a strange usage of the term "hardcoded", Normally, hardcoded
means that it is in the *code*, not a configuration file.


> ```
> [handler_hand02]
> class=FileHandler
> level=DEBUG
> formatter=form02
> args=('python.log', 'w')
> ```
> [code reference link](https://docs.python.org/3.4/library/logging.config.html#logging-config-fileformat)
> 
> Desired Behavior:
> On each run of the program, a new logfile is created in the `logs/`
> directory named "<timestamp>_program.log".
> 
> Current Behavior: 
> The format in the example above overwrites a single file called
> "python.log" on each run, which is not the desired behavior.
> 
> Question: Is there a standard procedure for using .ini files to create
> a new logfile prepended with the current Unix timestamp on each run of
> the program?

You would have to use a different class for that. I don't know one
offhand which implements the behaviour you want, but for example
TimedRotatingFileHandler switches log files after a configurable
interval. So for example

    class=TimedRotatingFileHandler
    when=H

would start a new log every hour (and rename the old log to contain a
timestamp).

You may need to write a handler which implements the behaviour you want.
Or maybe there is one on PyPi.

        hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20200529/657721a5/attachment.sig>


More information about the Python-list mailing list