2021-10-18-0738Z


For obscure reasons, I wanted to log certain messages to a dynamically created webpage, in addition to stderr and a logfile. Googling brought up all kinds of possible ways, but I finally settled on extending logging.NullHandler:

class DequeHandler(logging.NullHandler):
    '''
    simple handler to append log record to queue
    '''
    def handle(self, record):
        if hasattr(record, 'to_page'):
            MESSAGE_QUEUE.append(':'.join([
                record.name,
                record.levelname,
                record.msg % record.args
            ]))

logging.getLogger('').addHandler(DequeHandler())

Then, when the webpage is generated, I just loop through the deque. To have a message inserted into it, you need to add the extra parameter to the logging call: logging.warning('This logs to all handlers', extra={'to_page': True}).

Due to my not checking, it would still go to the queue if `to_page` were set to False, but I'm not even going to worry about that.

I've been lax on updating my blog lately, preferring to facebook and tweet whatever I had to say. But I've got to wean myself off those timewasters.

Back to blog or home page

last updated 2021-12-17 23:55:08. served from tektonic.jcomeau.com