Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- from datetime import datetime
- from StringIO import StringIO
- from functools import wraps
- def truncate(item, maxlen=20):
- msg = str(item)
- if len(msg) <= maxlen:
- return msg
- else:
- return msg[:maxlen-3] + "..."
- class Logger(object):
- """
- Base class for logging operations
- Attributes
- ----------
- out : list
- List of output buffers.
- default = [sys.stdout]
- hsep : string
- Separator between the datetime stamp and each log entry.
- default = " : "
- isep : string
- Separator between individual log entry items.
- default = ", "
- lsep : string
- Line separator for log entries.
- default = "\n"
- bsize : int
- Max buffer size (in lines) before an automatic flush().
- default = 1
- dtformat : string
- Formatting string for the datetime.now().
- default = "{0.month}/{0.day}/{0.year} {0.hour}:{0.minute}:{0.second}"
- debug : bool
- Toggle for logging actions.
- default = True
- Methods
- -------
- write(*args)
- Write args, separated by a item separator to the log buffer.
- flush()
- Flush the log buffer to the output buffers.
- close()
- Closes all output buffers (will not close stdout or stderr).
- Sets debug to False. (Attempting to write to the log after
- closing will generate errors.)
- log(obj, methods=None)
- Decorates the object methods in methods so that they will
- write to the log on execution. If methods is None, log will
- decorate the obj.__call__ method.
- logFunc(func)
- Decorates a function so that it will write to the log on execution.
- """
- def __init__(self, **options):
- self.out = options.get("out", [sys.stdout])
- self.hsep = options.get("hsep", " : ")
- self.isep = options.get("isep", ", ")
- self.lsep = options.get("lsep", "\n")
- self.bsize = options.get("bsize", 1)
- self.dtformat = options.get(
- "dtformat",
- "{0.month}/{0.day}/{0.year} {0.hour}:{0.minute}:{0.second}"
- )
- self._buffer = StringIO()
- self._linecount = 0
- self._lastpos = 0
- self.debug = options.get("debug", True)
- def _checkflush(self):
- if self._linecount >= self.bsize:
- self.flush()
- def write(self, *args):
- self._buffer.write(''.join(
- [self.dtformat.format(datetime.now()),
- self.hsep,
- self.isep.join(args),
- self.lsep]))
- self._linecount += 1
- self._checkflush()
- def flush(self):
- self._buffer.seek(self._lastpos)
- output = self._buffer.read()
- for out in self.out:
- out.write(output)
- self._linecount = 0
- self._lastpos = self._buffer.tell()
- def close(self):
- self.flush()
- for out in self.out:
- if not hasattr(out, "oid"):
- out.close()
- self.debug = False
- def _helper(self, f):
- @wraps(f)
- def wrapper(*args, **kwargs):
- result = f(*args, **kwargs)
- if self.debug:
- towrite = [f.__name__] + map(truncate, args)
- self.write(*towrite)
- return result
- return wrapper
- def log(self, obj, methods=None, flags=None):
- if methods is None:
- setattr(obj, "__call__", self._helper(obj.__call__))
- else:
- for method in methods:
- setattr(obj, method, self._helper(getattr(obj, method)))
- def logFunc(self, func):
- return self._helper(func)
- if __name__ == '__main__':
- l = Logger(
- out=[sys.stdout, sys.stderr],
- bsize=1)
- class A(object):
- def foo(self, name):
- return "Hello, {}".format(name)
- def bar(self, name):
- return "Goodbye, {}".format(name)
- def baz(self, name):
- return (self, name)
- a = A()
- print(a.foo("Joel"))
- print(a.bar("James"))
- l.log(a, ["foo", "baz"])
- print(a.foo("Bob"))
- print(a.bar("Charles"))
- print(a.baz("Jack"))
- def foo(name):
- return name * 2
- print(foo("joel"))
- l.log(foo)
- print(foo("joey"))
Advertisement
Add Comment
Please, Sign In to add comment