Configuring Multiple Loggers in Python

June 17, 2015

At times you may want to have multiple loggers in your application, e.g. one for a payments module and another for a messaging module. I’m going to explain how to set this up in your application, as well as show some examples for usage.

First, create a file, maybe call it

Import some required libraries

import logging

from logging import FileHandler
from logging import Formatter

For example, if our app is called wasted_meerkats, and we have 2 modules, payments and messaging, we could set up different loggers as follows:

    "%(asctime)s [%(levelname)s]: %(message)s in %(pathname)s:%(lineno)d")
LOG_LEVEL = logging.INFO

# messaging logger
MESSAGING_LOG_FILE = "/tmp/wasted_meerkats/messaging.log"

messaging_logger = logging.getLogger("wasted_meerkats.messaging")
messaging_logger_file_handler = FileHandler(MESSAGING_LOG_FILE)

# payments logger
PAYMENTS_LOG_FILE = "/tmp/wasted_meerkats/payments.log"
payments_logger = logging.getLogger("wasted_meerkats.payments")

payments_file_handler = FileHandler(PAYMENTS_LOG_FILE)

To test this out, you could create another file, called and put the following code in it:

from logger import messaging_logger
from logger import payments_logger"The meerkats are drunk!")"Who knows where they got the money?!")

Create the log directories above

$ mkdir /tmp/wasted_meerkats && touch /tmp/wasted_meerkats/messaging.log /tmp/wasted_meerkats/payments.log

In a separate tab, tail the logs

tail -f /tmp/wasted_meerkats/*log

Then test it out!

$ python

The log output should look something like this:

==> /tmp/wasted_meerkats/messaging.log <==
2015-10-17 20:55:05,942 [INFO]: The meerkats are drunk! in

==> /tmp/wasted_meerkats/payments.log <==
2015-10-17 20:55:05,942 [INFO]: Who knows where they got the money?! in

Having all the loggers in one file can help organize your project better.

I’ve put all the code used here as a gist here:

Happy coding people!