Skip to content

Instantly share code, notes, and snippets.

@yubessy
Created January 15, 2017 03:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yubessy/d60cff56940dcf7d430b32d08bcd7221 to your computer and use it in GitHub Desktop.
Save yubessy/d60cff56940dcf7d430b32d08bcd7221 to your computer and use it in GitHub Desktop.
Python logging using context

cxtlog

Contextual Logger for Python

Usage

>>> logging.basicConfig(level=logging.INFO)
>>> logger = logging.getLogger()
>>> cxtlgr = cxtlog.wrap(logger)
>>> with cxtlgr.cxt('test'):
...     print('Hello')
...
INFO:root:Start: test
Hello
INFO:root:Complete: test
>>> with cxtlgr.cxt('error'):
...     1 / 0
...
INFO:root:Start: error
ERROR:root:Fail: error
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero
class LoggingContext:
def __init__(self, logger, name):
self._logger = logger
self._name = name
def __enter__(self):
self._start()
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is None:
self._complete()
else:
self._fail()
def _start(self):
self._logger.info('Start: {}'.format(self._name))
def _complete(self):
self._logger.info('Complete: {}'.format(self._name))
def _fail(self):
self._logger.error('Fail: {}'.format(self._name))
class ContextualLogger:
def __init__(self, logger):
self._logger = logger
def cxt(self, name):
return LoggingContext(self._logger, name)
def wrap(logger):
return ContextualLogger(logger)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment