Python logging: Retrieving the last log record from a handler

F

Frank Aune

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
 
V

Vinay Sajip

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

Prepare to be surprised ;-)

Except for the MemoryHandler, which is designed specifically as a
buffer for logging events, the handlers in the logging package do not
store the last record they processed. (Neither do loggers, filters or
formatters, all of which get to see records as they are processed.)

Best regards,

Vinay Sajip
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top