
from contextlib import contextmanager
import logging

current_context = []
current_context_str = ''

@contextmanager
def log_context(name):
	global current_context, current_context_str

	current_context.append(unicode(name))
	current_context_str = '/'.join(current_context)
	try:
		yield
	except Exception as e:
		if not hasattr(e, 'context'):
			e.context = current_context_str
		raise
	finally:
		current_context.pop()
		current_context_str = '/'.join(current_context)

class IndentFilter(logging.Filter):
	def filter(self, record):
		record.context = current_context_str
		record.indent = len(current_context)*'  '
		return True

