Skip to content

Instantly share code, notes, and snippets.

@techtonik
Created October 16, 2011 16:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techtonik/1291125 to your computer and use it in GitHub Desktop.
Save techtonik/1291125 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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
Copy link
Author

added depth parameter that is useful for wrappers

@techtonik
Copy link
Author

imported logging

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