Skip to content

Instantly share code, notes, and snippets.

@yubessy
Created Jan 15, 2017
Embed
What would you like to do?
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