[Twisted-Python] Logging Framework

Moshe Zadka m at moshez.org
Tue Aug 21 17:33:59 EDT 2001


Or: How to do logging the proper way.

Disclaimer: I have not profiled the ideas described here yet.

twisted.python.log:

DEBUG, WARNING, NORMAL, IMPORTANT, CRITICAL = range(5)
priorities = 'DEBUG', 'WARNING', 'NORMAL', 'IMPORTANT', 'CRITICAL'

class FileLogsink:

    def __init__(self, fp):
        self.fp = fp

    def log(msg, category, priority):
        now = time.ctime(time.time())
        priority = priorities[priority]
        self.fp.write('[%(now)s] - %(priority)s - [%(category)s] %(msg)s' % 
                      vars())


class SysLogsink:
    ...

sink = None
min_priority = WARNING
min_priorities = {}

def msg(msg, category=None, priority=NORMAL):
    if priority >= min_priorities.get(category, min_priority):
        sink.log(msg, category, priority)

def startLogging(newSink):
    import sys
    global sink
    sink = newSink
    sys.stdout = SinkFileWrapper('stdout')
    sys.stderr = SinkFileWrapper('stderr')

def startLoggingFile(name):
    startLogging(open(name, 'ab+'))

class SinkFilewrapper:

    queued = ''

    def __init__(self, name):
        self.name = name

    def write(self, data):
        data = string.split(self.queued+data, '\n')
        self.queued = data[-1]
        for line in data[:-1]:
            msg(line, self.name, DEBUG)
            

class Logsource:

    '''mixin for classes wanting to log.

    Usage:

    class MyLoggingClass(Logsource):
        logCategory = 'MyThing'

        def someMethod(self, foo, bar):
            if foo==bar:
                self.log("foo should not be the same as bar", WARNING)
    '''
    logCategory = None

    def log(message, priority=NORMAL):
        msg(message, self.logCategory, priority)



-- 
The Official Moshe Zadka FAQ: http://moshez.geek
The Official Moshe Zadka FAQ For Dummies: http://moshez.org
Read the FAQ





More information about the Twisted-Python mailing list