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?
Little fix to excellent Denis's solution.
Logging name system based on hierarchical structure:
For example, when you setLevel() for some logger, this level will be also applied to child loggers. That's why you might want your formatter will be used for logger and it's child loggers too. For example,
'one.two'
formatter should also be applied to'one.two.three'
logger (if no formatter for'one.two.three'
set). Here's version of DispatchingFormatter that do job (Python 3 code):Example:
It's easy to dispatch to different formatters based on
record.name
. Below is prove-of-concept sample code:Another way is to open file manually and create two stream handlers from it with different formatters.