Skip to content

Instantly share code, notes, and snippets.

@andreycizov
Created July 28, 2018 15:17
Show Gist options
  • Save andreycizov/bd0bcd30eb0f1626b5173ff253c7c5de to your computer and use it in GitHub Desktop.
Save andreycizov/bd0bcd30eb0f1626b5173ff253c7c5de to your computer and use it in GitHub Desktop.
trc.py: Python automatic logger generation from the calling function (> 3.6)
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