How to check if a logger exists

Workaround that works for me and possibly you:

When you create a logger for your own code, you will almost certainly create a logger with handlers (file handler and/or console handler). When you have not yet created a logger and you get the 'root' logger by

logger = logging.getLogger()

then this logger will have no handlers yet. Therefore, I always check whether the logger above results in a logger that has handlers by

logging.getLogger().hasHandlers()

So I create a logger only if the root logger does not have handlers:

logger = <create_my_logger> if not logging.getLogger().hasHandlers() else logging.getLogger()

The "create_my_logger" snippet represents my code/function that returns a logger (with handlers).


WARNING. This is not documented. It may change without notice.

The logging module internally uses a single Manager object to hold the hierarchy of loggers in a dict accessible as:

import logging
logging.Logger.manager.loggerDict

All loggers except the root logger are stored in that dict under their names.

There are few examples on the net: http://code.activestate.com/lists/python-list/621740/ and https://michaelgoerz.net/notes/use-of-the-logging-module-in-python.html (uses Python 2 print)