Skip to content

Instantly share code, notes, and snippets.

@liladas
Last active April 5, 2018 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liladas/dbeb87d29c268f3c2212e9205500d2f2 to your computer and use it in GitHub Desktop.
Save liladas/dbeb87d29c268f3c2212e9205500d2f2 to your computer and use it in GitHub Desktop.
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))
@classmethod
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!")
log.info("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...
## [ERROR] WE HAVE WORK TO DO!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment