jncornett

After definition logger

Oct 31st, 2012
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.45 KB | None | 0 0
  1.  
  2. import sys
  3. from datetime import datetime
  4. from StringIO import StringIO
  5. from functools import wraps
  6.  
  7. def truncate(item, maxlen=20):
  8.     msg = str(item)
  9.     if len(msg) <= maxlen:
  10.         return msg
  11.     else:
  12.         return msg[:maxlen-3] + "..."
  13.    
  14. class Logger(object):
  15.  
  16.     """
  17.    Base class for logging operations
  18.  
  19.    Attributes
  20.    ----------
  21.    out : list
  22.        List of output buffers.
  23.        default = [sys.stdout]
  24.    hsep : string
  25.        Separator between the datetime stamp and each log entry.
  26.        default = " : "
  27.    isep : string
  28.        Separator between individual log entry items.
  29.        default = ", "
  30.    lsep : string
  31.        Line separator for log entries.
  32.        default = "\n"
  33.    bsize : int
  34.        Max buffer size (in lines) before an automatic flush().
  35.        default = 1
  36.    dtformat : string
  37.        Formatting string for the datetime.now().
  38.        default = "{0.month}/{0.day}/{0.year} {0.hour}:{0.minute}:{0.second}"
  39.    debug : bool
  40.        Toggle for logging actions.
  41.        default = True
  42.  
  43.    Methods
  44.    -------
  45.    write(*args)
  46.        Write args, separated by a item separator to the log buffer.
  47.    flush()
  48.        Flush the log buffer to the output buffers.
  49.    close()
  50.        Closes all output buffers (will not close stdout or stderr).
  51.        Sets debug to False. (Attempting to write to the log after
  52.        closing will generate errors.)
  53.    log(obj, methods=None)
  54.        Decorates the object methods in methods so that they will
  55.        write to the log on execution. If methods is None, log will
  56.        decorate the obj.__call__ method.
  57.    logFunc(func)
  58.        Decorates a function so that it will write to the log on execution.
  59.    """
  60.    
  61.     def __init__(self, **options):
  62.         self.out = options.get("out", [sys.stdout])
  63.         self.hsep = options.get("hsep", " : ")
  64.         self.isep = options.get("isep", ", ")
  65.         self.lsep = options.get("lsep", "\n")
  66.         self.bsize = options.get("bsize", 1)
  67.         self.dtformat = options.get(
  68.             "dtformat",
  69.             "{0.month}/{0.day}/{0.year} {0.hour}:{0.minute}:{0.second}"
  70.             )
  71.        
  72.         self._buffer = StringIO()
  73.         self._linecount = 0
  74.         self._lastpos = 0
  75.         self.debug = options.get("debug", True)
  76.        
  77.     def _checkflush(self):
  78.         if self._linecount >= self.bsize:
  79.             self.flush()
  80.            
  81.     def write(self, *args):
  82.         self._buffer.write(''.join(
  83.             [self.dtformat.format(datetime.now()),
  84.             self.hsep,
  85.             self.isep.join(args),
  86.             self.lsep]))
  87.  
  88.         self._linecount += 1
  89.  
  90.         self._checkflush()
  91.    
  92.     def flush(self):
  93.         self._buffer.seek(self._lastpos)
  94.         output = self._buffer.read()
  95.         for out in self.out:
  96.             out.write(output)
  97.  
  98.         self._linecount = 0
  99.         self._lastpos = self._buffer.tell()
  100.        
  101.     def close(self):
  102.         self.flush()
  103.         for out in self.out:
  104.             if not hasattr(out, "oid"):
  105.                 out.close()
  106.  
  107.         self.debug = False
  108.  
  109.     def _helper(self, f):
  110.         @wraps(f)
  111.         def wrapper(*args, **kwargs):
  112.             result = f(*args, **kwargs)
  113.  
  114.             if self.debug:
  115.                 towrite = [f.__name__] + map(truncate, args)
  116.                 self.write(*towrite)
  117.  
  118.             return result
  119.         return wrapper
  120.  
  121.     def log(self, obj, methods=None, flags=None):
  122.         if methods is None:
  123.             setattr(obj, "__call__", self._helper(obj.__call__))
  124.         else:
  125.             for method in methods:
  126.                 setattr(obj, method, self._helper(getattr(obj, method)))
  127.  
  128.     def logFunc(self, func):
  129.         return self._helper(func)
  130.  
  131.    
  132.  
  133. if __name__ == '__main__':
  134.     l = Logger(
  135.         out=[sys.stdout, sys.stderr],
  136.         bsize=1)
  137.  
  138.     class A(object):
  139.         def foo(self, name):
  140.             return "Hello, {}".format(name)
  141.  
  142.         def bar(self, name):
  143.             return "Goodbye, {}".format(name)
  144.  
  145.         def baz(self, name):
  146.             return (self, name)
  147.  
  148.     a = A()
  149.  
  150.     print(a.foo("Joel"))
  151.     print(a.bar("James"))
  152.  
  153.     l.log(a, ["foo", "baz"])
  154.  
  155.     print(a.foo("Bob"))
  156.     print(a.bar("Charles"))
  157.     print(a.baz("Jack"))
  158.  
  159.     def foo(name):
  160.         return name * 2
  161.  
  162.     print(foo("joel"))
  163.  
  164.     l.log(foo)
  165.  
  166.     print(foo("joey"))
Advertisement
Add Comment
Please, Sign In to add comment