Created
October 11, 2013 13:10
-
-
Save stuaxo/6934395 to your computer and use it in GitHub Desktop.
Outline for a logger using with statements, aimed at spreadsheets.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from contextlib import contextmanager | |
| import Queue | |
| import threading | |
| import collections | |
| class Cursor(object): | |
| def __init__(self, worksheet): | |
| self.worksheet = worksheet | |
| self.col = 0 | |
| self.row = 0 | |
| def cursor_logger(cursor): | |
| def f(msg): | |
| print '{worksheet} Row#{row} Column#{col} {msg}'.format(msg=msg, col=cursor.col, row=cursor.row, worksheet=cursor.worksheet) | |
| return f | |
| def template_logger(template): | |
| def f(msg): | |
| print template.format(msg=msg) | |
| return f | |
| def default_log(msg): | |
| print msg | |
| class ContextualLogger(object): | |
| loggers = collections.defaultdict(list) | |
| @classmethod | |
| @contextmanager | |
| def log_mgr(cls, logger): | |
| thread = threading.current_thread() | |
| cls.loggers[thread].append(logger) | |
| yield logger | |
| try: | |
| cls.loggers[thread].pop() | |
| except IndexError: | |
| del cls.loggers[thread] | |
| @classmethod | |
| def get_logger(cls): | |
| thread = threading.current_thread() | |
| loggers = cls.loggers[thread] | |
| if loggers: | |
| return loggers[-1] | |
| else: | |
| return default_log | |
| return logger | |
| def log(msg): | |
| logger = ContextualLogger.get_logger() | |
| logger(msg) | |
| #log('hello') | |
| cursor1 = Cursor('Workbook 1') | |
| cursor2 = Cursor('Workbook 2') | |
| log('hello Z') | |
| with ContextualLogger.log_mgr(cursor_logger(cursor1)): | |
| log('hello cursor1') | |
| cursor1.row += 1 | |
| log('hello cursor1') | |
| with ContextualLogger.log_mgr(cursor_logger(cursor2)): | |
| log('hello cursor2') | |
| log('hello cursor1') | |
| log('hello cursor1') | |
| log('hello D') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment