is there a way to configure a python logger to call a custom function and pass it the logging message whenever it logs?
-
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.scottiedoo– scottiedoo2017-09-22 00:28:01 +00:00Commented Sep 22, 2017 at 0:28
-
I'll give it a try, thanks!guy.S– guy.S2017-09-22 09:25:08 +00:00Commented Sep 22, 2017 at 9:25
-
@guy.S Did you ever come up with a solution?gerrit– gerrit2020-11-17 17:43:33 +00:00Commented Nov 17, 2020 at 17:43
-
1@gerrit I've added an answer now (for either Python 2 or 3)xjcl– xjcl2020-12-09 04:42:01 +00:00Commented Dec 9, 2020 at 4:42
Add a comment
|
1 Answer
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