diff -r aaa62c8e5bd5 -r f13cf27a360b log_formatter.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/log_formatter.py Mon Feb 09 00:24:13 2009 +0200 @@ -0,0 +1,106 @@ +""" + Format LogLines into some other representation +""" + +from qmsk.web import helpers + +from log_line import LogTypes + +class LogFormatter (object) : + """ + Provides a method to format series of LogLines into various output formats, with varying themes + """ + + def __init__ (self, tz, timestamp_fmt="%H:%M:%S") : + """ + Initialize to format timestamps with the given timezone and timestamp + """ + + self.tz = tz + self.timestamp_fmt = timestamp_fmt + + def _format_line_text (self, line, template_dict) : + """ + Format the given line as text, using the given { type: string template } dict + """ + + # look up the template + template = template_dict[line.type] + + # build timestamp + timestamp = line.timestamp.astimezone(self.tz).strftime(self.timestamp_fmt) + + # format with dict + return template % dict( + timestamp = timestamp, + source = line.source, + data = line.data, + ) + + def format_txt (self, lines) : + """ + Format as plaintext + """ + + abstract + + def format_html (self, lines) : + """ + Format as HTML + """ + + abstract + +class IrssiTextFormatter (LogFormatter) : + """ + Implements format_txt for irssi-style output + """ + + # format definitions by type + __FMT = { + LogTypes.RAW : "%(timestamp)s %(data)s", + } + + def format_txt (self, lines) : + # ...handle each line + for line in lines : + # using __TYPES + yield self._format_line_text(line, self.__FMT) + +class IrssiFormatter (IrssiTextFormatter) : + """ + Implements plain black-and-white irssi-style formatting + """ + + def format_html (self, lines) : + """ + Just uses format_txt, but wraps in

+        """
+        
+        # open pre
+        yield "
"
+        
+        # format using IrssiTextFormatter
+        for line in self.format_txt(lines) :
+            # escape HTML
+            yield helpers.escape(line)
+
+        # close pre
+        yield "
" + +# define formatters by name +FORMATTERS = { + 'irssi': IrssiFormatter, +} + +def by_name (name) : + """ + Lookup and return a formatter by name + + XXX: uses default timezone/timefmt + """ + + import pytz + + return FORMATTERS[name](pytz.utc) +