Skip to content

Instantly share code, notes, and snippets.

@daltonmatos
Created January 20, 2013 23:29
Show Gist options
  • Save daltonmatos/4582563 to your computer and use it in GitHub Desktop.
Save daltonmatos/4582563 to your computer and use it in GitHub Desktop.
Dynamic logging.getLogget(__name__) implementation
class LoggerProxy(object):
def _setup_logger(self, logger):
console = logging.StreamHandler()
logger.addHandler(console)
logger.setLevel(logging.INFO)
logger._configured = True
def __getattr__(self, attr):
_configured = False
stack = inspect.stack()
frame = stack[1][0]
logname = frame.f_globals['__name__']
_logger = logging.getLogger(name=logname)
if hasattr(_logger, '_configured'):
_configured = getattr(_logger, '_configured')
if not _configured:
self._setup_logger(_logger)
return getattr(_logger, attr)
logger = LoggerProxy()
# This could go insie your "myproject.core" module, so you can get the logger by running:
from myproject.core import logger
# This code gives you a logger with the name of the package from here it is *used*. Used, not imported. An example:
# Inside the module myproject.tasks.scheduled you may have:
from myproject.core import logger
logger.info("Testing the Dynamic logger")
# The logger that have the info() method called is a logger named "myproject.tasks.scheduled",
# got with logging.getLogger("myproject.tasks.scheduled").
#Remember that if you pass this logger to function that is in another module,
#the logger will have the name of this other moduke:
# Insie myproject.modules.module_one
from myproject.core import logger
from myproject.modules.module_two import myfunc
myfunc(logger)
# In this example, if myfunc() uses the logger received, the logger will be a logger with name "myproject.modules.module_two"
# and not "myproject.modules.module_one".
# You can also add more logic to the __getattr__() method,
# for example if you want to have the *same* logger for all modules below myproject.tasks, you can do this by inspecting
# the value of the variable logname, that is the name of the moduile where the logger is being used.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment