Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Logging - Automatically get module.class name for log() caller

View inspectlog.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
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()
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
Owner

added depth parameter that is useful for wrappers

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.