Search code examples
pythonloggingcallbacknotificationsloguru

Loguru callback function when an error is logged


I'm moving a desktop application from Python's standard library logging to Loguru, and want to have a text box in the user interface that contains logging information.

Is there a way to hook into Loguru error-level logging which allows the log message to be sent to a callback function? This would allow me to update the user interface with the latest error messages. For example,

from loguru import logger

def error_callback(msg: str):
    # Do something with the error message
    pass

logger.add_callback(error_callback) # <-- Does something like this exist?

# So when I do this...
logger.error("Oh noes")
# ... the callback is called with the argument `"Oh noes"`

Solution

  • You can't add a callback for only errors, but you can add a callback for every log and inside of that check if it is an error. The idea is the same as Adapters do in stdlib logging, with the only difference that loguru calls it patch.

    from loguru import logger
    
    def error_callback(record):
        if record['level'].name == 'ERROR':
            print('logging an error')
            # the log message is available as: record['message']
    
    logger = logger.patch(error_callback)
    
    logger.error('error')