Skip to content

Instantly share code, notes, and snippets.

@stuaxo
Created October 11, 2013 13:16
Show Gist options
  • Select an option

  • Save stuaxo/6934495 to your computer and use it in GitHub Desktop.

Select an option

Save stuaxo/6934495 to your computer and use it in GitHub Desktop.
{
"metadata": {
"name": "tmp"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"from contextlib import contextmanager\n",
"import Queue\n",
"\n",
"import threading\n",
"import collections\n",
"\n",
"class Cursor(object):\n",
" def __init__(self, worksheet):\n",
" self.worksheet = worksheet\n",
" self.col = 0\n",
" self.row = 0\n",
" \n",
"\n",
"def cursor_logger(cursor):\n",
" def f(msg):\n",
" print '{worksheet} Row#{row} Column#{col} {msg}'.format(msg=msg, col=cursor.col, row=cursor.row, worksheet=cursor.worksheet)\n",
" return f\n",
" \n",
"def template_logger(template):\n",
" def f(msg):\n",
" print template.format(msg=msg)\n",
" return f\n",
"\n",
"def default_log(msg):\n",
" print msg\n",
" \n",
"class ContextualLogger(object):\n",
" loggers = collections.defaultdict(list)\n",
" \n",
" @classmethod\n",
" @contextmanager\n",
" def log_mgr(cls, logger):\n",
" thread = threading.current_thread()\n",
" \n",
" cls.loggers[thread].append(logger)\n",
" yield logger\n",
" \n",
" try:\n",
" cls.loggers[thread].pop()\n",
" except IndexError:\n",
" del cls.loggers[thread]\n",
" \n",
" \n",
" @classmethod\n",
" def get_logger(cls):\n",
" thread = threading.current_thread()\n",
" loggers = cls.loggers[thread]\n",
" if loggers:\n",
" return loggers[-1]\n",
" else:\n",
" return default_log\n",
" return logger\n",
" \n",
"def log(msg):\n",
" logger = ContextualLogger.get_logger()\n",
" logger(msg)\n",
"\n",
"#log('hello')\n",
"cursor1 = Cursor('Workbook 1')\n",
"cursor2 = Cursor('Workbook 2')\n",
"log('hello Z')\n",
"with ContextualLogger.log_mgr(cursor_logger(cursor1)):\n",
" log('hello cursor1')\n",
" cursor1.row += 1\n",
" log('hello cursor1')\n",
" with ContextualLogger.log_mgr(cursor_logger(cursor2)):\n",
" log('hello cursor2')\n",
" \n",
" log('hello cursor1')\n",
" log('hello cursor1')\n",
" \n",
"log('hello D')"
],
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment