is there a way to configure a python logger to call a custom function and pass it the logging message whenever it loggs? Thanks!
Subclass logging.Handler
and implement the emit
method:
import logging
class MyHandler(logging.Handler):
def emit(self, record):
print('custom handler called with\n ', record)
logger = logging.getLogger(__name__)
logger.addHandler(MyHandler()) # or: logger.handlers = [MyHandler()]
logger.warning('Log 1')
logger.warning('Log 2')
custom handler called with
<LogRecord: __main__, 30, /home/jan/Dropbox/py/so_logging.py, 9, "Log 1">
custom handler called with
<LogRecord: __main__, 30, /home/jan/Dropbox/py/so_logging.py, 10, "Log 2">
The specific message being logged can be accessed as record.msg
(unformatted string) or self.format(record)
(formatted string, in case you added a timestamp or loglevel)
Additionally: If you also override the logging.Handler
's __init__
method, it is important to do the super call to it in the subclass.
Standard caveats for the logging
module apply:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With