logging: How do you change the format?

Richard Jones rjones at ekit-inc.com
Sat Jan 18 21:33:52 EST 2003


On Sun, 19 Jan 2003 12:31 pm, Kevin Smith wrote:
> I've been playing around with the logging package in Python 2.3.  The
> documentation is pretty skimpy on the examples and there are no examples
> on how to change the format of the messages.  Can someone "in the know"
> please post an example of how to do this?  Thank you.

You will need to create your own Formatter class, and attach it to a Handler. 
I think. If you can figure a way to get access to your Handler, you can call 
setFormatter() on it. There doesn't appear to be any way to _remove_ handlers 
though, apart from "logger.handlers = []".

I'm still trying to figure a sane way to use the thing. My current setup (very 
much in development) is looking like:


# at the top of the main file
from logging import logger


# when I have successfully determined what the logging configuration
# should be (from command-line or config file), I can call:
def configureLogging(log_file=None, log_level=None):
    ''' Configure the (global) logger using variables from the (global)
        config.

	Config items used:
         log_file  - the file to log to
         log_level - the level of message to log
    '''
    if log_file is None:
        log_file = config['log_file']
    if log_level is None:
        log_level = config['log_level']
    # XXX confirm we have valid log_file and log_level

    logging._acquireLock()
    try:
        # clear out current handler
        logger.handlers = []
        hdlr = FileHandler(log_file)
        hdlr.setFormatter(Formatter('%(asctime)s %(level)s %(message)s'))
        logger.addHandler(hdlr)
        logger.setLevel(log_level)
    finally:
        logging._releaseLock()


# now at the very start of the script, we do this so messages will make it
# to the console
logger.basicConfig()


I'd really like to see a top-level function in the logging module:

def configureLogging(file, level=INFO):
    ''' Configure the root logger to log to "file"
    '''

since that's probably the most common usage.


       Richard






More information about the Python-list mailing list