Python logging: Retrieving the last log record from a handler

Frank Aune Frank.Aune at broadpark.no
Mon Mar 3 06:41:26 EST 2008


Hi,

I'm using a log hierarchy in my application, and sometimes I find myself 
wanting to retrieve the latest log message written to the root logger. 
(Typical usage might be displaying the latest log message at all times in a 
GUI).

The only way I've found how to solve this, is by adding a custom loghandler:

---
class LastRecordHandler(logging.Handler):

    def __init__(self):
        logging.Handler.__init__(self)
        self.lastRecord = None  

    def emit(self, record):
        self.lastRecord = record

    def getRecord(self):
        return self.lastRecord.getMessage()
---

I will be fairly surprised if this functionality is not already built-in for 
the default logging handlers, but so far I've been unable to figure out how 
to pull it of without the custom loghandler above.

The kind of functionality I'm looking for is something like:

self.log = logging.getLogger('GUI')
(...)
lastRecord = self.log.getLastRecord()
# Display lastRecord in GUI

Is this possible in some way, or do I need to extend the default logging 
handlers in order to archieve this?

Thanks,
Frank





More information about the Python-list mailing list