Python 2
class StoredLogger(logging.Logger):
def makeRecord(self, *args, **kwargs):
...
return logging.LogRecord(*args, **kwargs)
logging.setLoggerClass(StoredLogger)
Within makeRecord, you could add a call to a function like store_message, whose behavior you define.
def store_message(*args, **kwargs):
"""Write a message to the database"""
...
Python 3.2+
Changed in version 3.2: The creation of a LogRecord has been made more configurable by providing a factory which is used to create the record. The factory can be set using getLogRecordFactory() and setLogRecordFactory() (see this for the factory’s signature).
old_factory = logging.getLogRecordFactory()
def new_factory(*args, **kwargs):
record = old_factory(*args, **kwargs)
record.custom_attribute = 0xDECAFBAD
return record
logging.setLogRecordFactory(new_factory)
You would add your call to store_message into your record_factory.
def record_factory(*args, **kwargs):
store_message(*args, **kwargs)
global old_factory
return old_factory(*args, **kwargs)
Then, when you use something like logging.info('foo'), it will pass through store_message, then resume its normal behavior by writing to its out-stream. You may want to consider renaming record_factory to something more descriptive like stored_record_factory.