Reputation: 3944
I am writing a custom Python logging handler that puts the system in an error state whenever there is a logging error. To do this, I am overriding the handleError() method in my custom handler.
Once the system goes into the error state, I need to monitor the logger and occasionally test whether it's recovered or not. In order to do this, I need a reference to the actual logger that had the error from in the handleError() method.
How can I access the logger from its handler's handleError() method?
Example of what I'm trying to do:
class MyFileHandler(WatchedFileHandler):
def handleError(self, record):
logger_that_had_the_error = ???????????
put_system_in_error_state(f"Logging failure ({record.msg})")
start_monitoring_logger(logger_that_had_the_error)
super().handleError(record)
What should I replace the ??????????? with?
Upvotes: 0
Views: 125
Reputation: 5185
When handleError
was called there wasn't an error in the logger, there was an error in the emit()
method of the handler. The same handler could be attached to any number of loggers, and might not even be attached to the logger that originally received the log, but any of its ancestors in the logging hierarchy.
To get the name of the logger that originated the log for which the handler had an error you can access the name
property of the LogRecord
object. To get the actual logger object you can use the name. So to fill this into your code:
def handleError(self, record):
logger_that_had_the_error = record.name
# or if you want the logger object:
# logger_that_had_the_error = logging.getLogger(record.name)
Upvotes: 1