Skip to content

Instantly share code, notes, and snippets.

@abduakhatov
Created February 5, 2022 09:00
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 abduakhatov/78f1b109446169058461fc6efcfb276e to your computer and use it in GitHub Desktop.
Save abduakhatov/78f1b109446169058461fc6efcfb276e to your computer and use it in GitHub Desktop.
Logger as a decorator
import logging
from functools import wraps
def logged(cls=None, *, name=''):
def logged_for_init(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
logger_name = name or self.__class__.__name__
self.log = logging.getLogger(logger_name)
return func(self, *args, **kwargs)
return wrapper
def wrap(cls):
cls.__init__ = logged_for_init(cls.__init__)
return cls
return wrap if cls is None else wrap(cls)
@logged
class MyClass:
def __init__(self):
self.log.info("We need to go deeper")
import logging
def logged(cls=None, *, name=""):
def wrap(cls):
cls.log = logging.getLogger(name or cls.__name__)
return cls
return wrap if cls is None else wrap(cls)
@logged(name="Arthur")
class MyClass:
def __init__(self):
self.log.info("True inspiration is impossible to fake")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment