Created
July 28, 2018 15:17
-
-
Save andreycizov/bd0bcd30eb0f1626b5173ff253c7c5de to your computer and use it in GitHub Desktop.
trc.py: Python automatic logger generation from the calling function (> 3.6)
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
def trc(postfix: Optional[str] = None) -> logging.Logger: | |
""" | |
Automatically generate a logger from the calling function | |
:param postfix: append another logger name on top this | |
:return: instance of a logger with a correct path to a current caller | |
""" | |
x = inspect.stack()[1] | |
code = inspect.currentframe().f_back.f_code | |
func = [obj for obj in gc.get_referrers(code) if inspect.isfunction(obj)][0] | |
mod = inspect.getmodule(x.frame) | |
parts = (mod.__name__, func.__qualname__) | |
if postfix: | |
parts += (postfix,) | |
logger_name = '.'.join(parts) | |
return logging.getLogger(logger_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment