Created
October 16, 2011 16:44
-
-
Save techtonik/1291125 to your computer and use it in GitHub Desktop.
Logging - Automatically get module.class name for log() caller
This file contains 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 inspect | |
import logging | |
def log(level, msg, depth=1): | |
"""Logging function that detects name of appropriate logger for calling | |
function in 'module.class' format. `depth` allows to specify a higher | |
frame in a call stack if you want to wrap this function. | |
""" | |
name = None | |
try: | |
parentframe = inspect.stack()[depth][0] | |
name = inspect.getmodule(parentframe).__name__ | |
if 'self' in parentframe.f_locals: | |
name = '%s.%s' % (name, parentframe.f_locals['self'].__class__.__name__) | |
finally: | |
del parentframe | |
logger = logging.getLogger(name) | |
logger.log(level, msg) | |
class A(object): | |
def hugo(self): | |
log(logging.INFO, 'hugo calling') | |
def another(): | |
log(logging.INFO, 'another call') | |
logging.basicConfig(level=logging.INFO, format="%(name)-15s %(message)s") | |
log(logging.INFO, 'root message') | |
a = A() | |
a.hugo() | |
another() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
imported logging