Created
February 5, 2022 09:00
-
-
Save abduakhatov/78f1b109446169058461fc6efcfb276e to your computer and use it in GitHub Desktop.
Logger as a decorator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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