Overriding Logging Config FileHandler Filename

Peter Otten __peter__ at web.de
Tue Oct 2 05:08:30 EDT 2007


Kenneth Love wrote:

> My (probably erroneous) speculation is that I can retrieve a handler
> specified in the INI file and dynamically change the filename argument
> to the desired value.  So far, I have been unable to figure out how to
> do this.

Here's a brute-force approach (tweaking the config file in memory before
passing it on to the logging module) that might work.

import logging.config

import ConfigParser
import StringIO

HANDLER = "handler"
LOGFILE = "alternate.log"

instream = open("some.cfg")
cp = ConfigParser.ConfigParser()
cp.readfp(instream)
section = "handler_%s" % HANDLER
oldargs = eval(cp.get(section, "args"))
cp.set(section, "args", (LOGFILE,) + oldargs[1:])

outstream = StringIO.StringIO()
cp.write(outstream)
outstream.seek(0)
logging.config.fileConfig(outstream)

logging.error("oops!")

Peter



More information about the Python-list mailing list