Search code examples
pythonpython-3.xloggingerror-handlingpython-logging

How to check if a logger exists


I've had to extend the existing logging library to add some features. One of these is a feature which lets a handler listen to any existing log without knowing if it exists beforehand. The following allows the handler to listen, but does not check if the log exists:

def listen_to_log(target, handler):
    logging.getLogger(target).addHandler(handler)

The issue is that I don't want any handler to listen to a log which isn't being logged to, and want to raise a ValueError if the log doesn't already exist. Ideally I'd do something like the following:

def listen_to_log(target, handler):
    if not logging.logExists(target):
        raise ValueError('Log not found')
    logging.getLogger(target).addHandler(handler)

So far I have been unable to find a function like logging.logExists, is there such a function, or a convenient workaround?


Solution

  • 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).