Extra fields for logging

Joan Miller peloko45 at gmail.com
Thu Dec 24 08:06:48 EST 2009


I'm trying to add some extra fields to logging, I'm following this
information [1] but it faills in my case.

# module logger.py
--------------------
import logging

class ExtraInfo(object):
    def __getitem__(self, name):
        if name == 'host':
            result = 'foo'
    def __iter__(self):
        keys = ['host',]
        keys.extend(self.__dict__.keys())
        return keys.__iter__()

def setup(filename='/tmp/foo.log'):
    log = logging.LoggerAdapter(logging.getLogger('foo'), ExtraInfo())
    #log = logging.LoggerAdapter(logging.getLogger('foo'), {'host':
'bar'})

    logging.basicConfig(
        level=logging.DEBUG,
        format=(
            "Date-Time: %(asctime)s\n"
            "Host: %(host)s\n"
            "%(levelname)s:\n"
            "%(message)s"),
        # %f => microseconds is not showed, bug?
        datefmt="%Y-%m-%dT%H:%M:%S%z",
        filename=filename,
        filemode='w')
--------------------

# module another.py
--------------------
import logger

logger.setup()
logging.getLogger('foo')
logging.error('testing ...')
--------------------

I get => KeyError: 'host'


-----------
System: Ubuntu 9.10 - Python 2.6.4
-----------

[1] http://docs.python.org/library/logging.html#adding-contextual-information-to-your-logging-output



More information about the Python-list mailing list