tags:

views:

70

answers:

1

Is it possible to log to a single destination (i.e. using one FileHandler) with multiple loggers (i.e. logging.getLogger("base.foo") and logging.getLogger("base.bar")), and use different formatters for each of the loggers.

To my understanding it's only possible to assign one formatter to each handle. Maybe it's possible to associate the formatter with a logger rather than the handler?

+1  A: 

It's easy to dispatch to different formatters based on record.name. Below is prove-of-concept sample code:

import logging


class DispatchingFormatter:

    def __init__(self, formatters, default_formatter):
        self._formatters = formatters
        self._default_formatter = default_formatter

    def format(self, record):
        formatter = self._formatters.get(record.name, self._default_formatter)
        return formatter.format(record)


handler = logging.StreamHandler()
handler.setFormatter(DispatchingFormatter({
        'base.foo': logging.Formatter('FOO: %(message)s'),
        'base.bar': logging.Formatter('BAR: %(message)s'),
    },
    logging.Formatter('%(message)s'),
))
logging.getLogger().addHandler(handler)

logging.getLogger('base.foo').error('Log from foo')
logging.getLogger('base.bar').error('Log from bar')
logging.getLogger('base.baz').error('Log from baz')

Another way is to open file manually and create two stream handlers from it with different formatters.

Denis Otkidach