14

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

4
  • You should look sub classing and implementing your own logging Handler: docs.python.org/3.5/library/logging.html#handler-objects and implement the "emit" method where you can do anything you want with the record. Commented Sep 22, 2017 at 0:28
  • I'll give it a try, thanks! Commented Sep 22, 2017 at 9:25
  • @guy.S Did you ever come up with a solution? Commented Nov 17, 2020 at 17:43
  • 1
    @gerrit I've added an answer now (for either Python 2 or 3) Commented Dec 9, 2020 at 4:42

1 Answer 1

13

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.