[Tutor] Subclassing logging.Handler?

Alex Hall ahall at autodist.com
Wed Jul 6 13:01:07 EDT 2016


Regarding this project: I've gone ahead and tried a variant of it. I wanted
to log to an HTML file, since those are much easier to look at with a
screen reader and so I could get used to the concepts involved. Here's what
I've come up with so far. I'll ask the question, then paste the code. I'm
getting an error on the self.stream.write line in _open that
"'ADTimedRotatingLogFileHandler' has no attribute stream". If I'm
subclassing TimedRotatingFileHandler, how can it not have stream?

import logging
import logging.handlers as logHandlers
class ADTimedRotatingLogFileHandler(logHandlers.TimedRotatingFileHandler):

    def __init__(self, filename, when, interval, backupCount, title):
        """Most parameters are for the superclass, but 'title' is the title
you want your HTML file to have."""
        super(ADTimedRotatingLogFileHandler, self).__init__(filename, when,
interval, backupCount)
        self._title = title

    def _open(self):
        super(ADTimedRotatingLogFileHandler, self)._open()
        self.stream.write("""<html>
<head>
<title>%s</title>
</head>
<body>
""" %(self._title))

    def close(self):
        self.stream.write("""
</body>
</html>""")
        super(ADTimedRotatingLogFileHandler, self).close()


On Wed, Jul 6, 2016 at 8:32 AM, Alex Hall <ahall at autodist.com> wrote:

> Hey list,
> Another day, another Python experiment. I'm wondering what methods I'd
> have to implement in a custom subclass of logger.Handler.
>
> Currently, the recurring jobs I have written log their events to a file
> each time they run. That's fine, but it doesn't let me keep
> easily-sorted/searched records. Even if I use a size-based log file
> handler, it'll get hard to search. I'm pondering logging to a database as
> well, so that the files will always have the most recent few runs, but the
> database will have everything. That means subclassing logger.Handler.
>
> I found the docs for this, but is emit() the only function I need to
> implement? There are things about i/o locks, formatting, and so on as well.
> How much do I need to do, and how much can I leave up to the super class?
> I'll have to call
> super(MyLogHandler, self).__init__()
> I know, but what else do I have to worry about? To be clear, I'm not
> asking about logging to a database, only what to do to make a Handler
> subclass capable of logging through whatever mechanisms I want. Thanks.
>
> --
> Alex Hall
> Automatic Distributors, IT department
> ahall at autodist.com
>



-- 
Alex Hall
Automatic Distributors, IT department
ahall at autodist.com


More information about the Tutor mailing list