Skip to content

@techtonik /inspectlog.py
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
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()
@techtonik
Owner

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
Owner

added depth parameter that is useful for wrappers

@techtonik
Owner

imported logging

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.