]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/commitdiff
util: logging: refactor some common logging behavior into mixins
authorZooko O'Whielacronx <zooko@zooko.com>
Wed, 17 Dec 2008 00:38:07 +0000 (17:38 -0700)
committerZooko O'Whielacronx <zooko@zooko.com>
Wed, 17 Dec 2008 00:38:07 +0000 (17:38 -0700)
src/allmydata/util/log.py

index d8fb0786f8335db8aec948cbc8dbcd4acf1e3b3c..5c42531ed306dc46bbb4c3b7c00b44b41be6c2a7 100644 (file)
@@ -1,4 +1,6 @@
 
+import nummedobj
+
 from foolscap.logging import log
 from twisted.python import log as tw_log
 
@@ -24,3 +26,37 @@ def err(*args, **kwargs):
     if 'level' not in kwargs:
         kwargs['level'] = log.UNUSUAL
     return log.err(*args, **kwargs)
+
+class LogMixin(object):
+    """ I remember a msg id and a facility and pass them to log.msg() """
+    def __init__(self, facility=None, grandparentmsgid=None):
+        self._facility = facility
+        self._grandparentmsgid = grandparentmsgid
+        self._parentmsgid = None
+
+    def log(self, msg, facility=None, parent=None, *args, **kwargs):
+        if facility is None:
+            facility = self._facility
+        if parent is None:
+            pmsgid = self._parentmsgid
+        if pmsgid is None:
+            pmsgid = self._grandparentmsgid
+        msgid = log.msg(msg, facility=facility, parent=pmsgid, *args, **kwargs)
+        if self._parentmsgid is None:
+            self._parentmsgid = msgid
+        return msgid
+
+class PrefixingLogMixin(nummedobj.NummedObj, LogMixin):
+    """ I prepend a prefix to each msg, which includes my class and instance number as well as
+    a prefix supplied by my subclass. """
+    def __init__(self, facility=None, grandparentmsgid=None, prefix=''):
+        nummedobj.NummedObj.__init__(self)
+        LogMixin.__init__(self, facility, grandparentmsgid)
+
+        if prefix:
+            self._prefix = "%s(%s): " % (self.__repr__(), prefix)
+        else:
+            self._prefix = "%s: " % (self.__repr__(),)
+
+    def log(self, msg, facility=None, parent=None, *args, **kwargs):
+        return LogMixin.log(self, self._prefix + msg, facility, parent, *args, **kwargs)