Skip to content

Instantly share code, notes, and snippets.

@liladas liladas/
Last active Apr 5, 2018

What would you like to do?
Mock logger object with auto function and label generation
class Singleton(object):
''' singleton class only allows for one instantiation per python interpreter '''
_instance = None
def __new__(class_, *args, **kwargs):
''' override __new__ behavior to only return new instance if not previously instantiated '''
if not isinstance(class_._instance, class_):
class_._instance = object.__new__(class_, *args, **kwargs)
return class_._instance
class PrintLogger(Singleton):
''' class that mimics logging module syntax '''
_labels = ['debug', 'info', 'warn', 'error']
def __init__(self):
''' dynamically creates functions corresponding with each label '''
for _label in PrintLogger._labels:
setattr(self, _label, self._mk_func(_name=_label))
def _mk_func(self, _name="log"):
''' returns a logging function with a dynamically generated signature/label '''
def _log_function(msg="", _label=_name):
print("[%s] %s" % (_label.upper(), msg))
_log_function.__name__ = _name
return _log_function
log = PrintLogger()
if __name__=="__main__":
log = PrintLogger()
log.debug("Oh hi!")"Isn't this nice?")
log.warn("But you should knock it off...")
log.error("WE HAVE WORK TO DO!")
### Example output ###
## [DEBUG] oh hi!
## [INFO] isn't this nice.
## [WARN] but you should knock it off...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.