views:

77

answers:

1

I would like to log the module and classname by default in log messages from my request handlers.

The usual way to do this seems to be to set a custom format string by calling logging.basicConfig, but this can only be called once and has already been called by the time my code runs.

Another method is to create a new log Handler which can be passed a new log Formatter, but this doesn't seem right as I want to use the existing log handler that App Engine has installed.

What is the right way to have extra information added to all log messages in python App Engine, but otherwise use the existing log format and sink?

+1  A: 

I cooked this up by reading the logging module's __init__.py. I don't know if this is proper, but it seems to work:

import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    )

logging.info('Danger Will Robinson!')
# 03-31 20:00 root         INFO     Danger Will Robinson!
root=logging.getLogger()
hdlr=root.handlers[0]
fmt = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
hdlr.setFormatter(fmt)
logging.info('Danger Will Robinson!')
# root        : INFO     Danger Will Robinson!

This is the line that bothers me: hdlr=root.handlers[0] I couldn't find any method to politely request root's handlers, so I resorted to reaching inside root's data structure and pulling out the bit that I needed. I suppose this could break if logging were to change its implementation.

unutbu