sds sds - 22 days ago 8
Python Question

How to find out whether getLogger created a new object?

How do I find out whether

returned a new or an existing logger object?

The motivation is that I don't want to
addHandler
repeatedly to the same logger.

Answer

There doesn't seem to be a particularly clean way to do this... However, if you must, the source-code is a pretty good place to start looking in order to figure this out. Note that logging.getLogger is mostly a wrapper around logging.Logger.manager.getLogger.

The Manager keeps a mapping of names -> Logger (or Placeholder). If it has Logger in the slot designated by a given name, it will return it. Otherwise, it'll return a new Logger.

import logging
def has_logger(name):
    manager = logging.Logger.manager
    if name in manager.loggerDict:
        return isinstance(manager.loggerDict[name], logging.Logger)
    else:
        return False

Note that this only handles the case where you have named loggers. If you do logging.getLogger() (without passing a name), then it simply will return the root logger which is created at import time (and therefore, it is never new).

Another approach could be to get a logger and check that it's handlers list is smaller than you'd expect (i.e. if it isn't an empty list, then handlers have been added).

def has_handlers(logger):
    """Return True if logger has handlers, False otherwise."""
    return bool(logger.handlers)