import threading
from contextlib import contextmanager
import logging

thread_local = threading.local()


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


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


def init_thread():
	current_context = getattr(thread_local, 'current_context', None)
	if current_context is None:
		thread_local.current_context = []

	current_context_str = getattr(thread_local, 'current_context_str', None)
	if current_context_str is None:
		thread_local.current_context_str = ''

