Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Logging - Automatically get module.class name for log() caller
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
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__)
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()

techtonik commented Oct 16, 2011

4c4c15 - optimized a bit
3262ca - added depth parameter that is useful for wrappers
256e5f - imported logging

Current output looks like:

__main__        root message
__main__.A      hugo calling
__main__        another call

techtonik commented Oct 19, 2011

added depth parameter that is useful for wrappers


techtonik commented Oct 19, 2011

imported logging

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment