Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logger with a callback function

is there a way to configure a python logger to call a custom function and pass it the logging message whenever it loggs? Thanks!

like image 548
guy.S Avatar asked Sep 22 '17 00:09

guy.S


1 Answers

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:

  • The default loglevel is WARNING (so DEBUG/INFO aren't passed to emit)
  • A log record is passed to all handlers of a logger
    • After that, it is passed to its ancestor in the logging hierarchy recursively
like image 186
xjcl Avatar answered Sep 18 '22 11:09

xjcl