Created
October 6, 2009 12:38
-
-
Save y10h/202977 to your computer and use it in GitHub Desktop.
Auto-naming loggers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
""" | |
Logging facilities | |
""" | |
import sys | |
import logging | |
FUNC_LOGGERS = {} | |
MOD_LOGGERS = {} | |
def get_logging_level(): | |
if hasattr(sys, 'frozen'): | |
# under py2exe | |
return logging.INFO | |
else: | |
return logging.DEBUG | |
def logging_options(): | |
opts = { | |
'level': get_logging_level(), | |
'format': "%(asctime)s - %(name)s - %(levelname)s - %(message)s", | |
} | |
if hasattr(sys, 'frozen'): | |
# under py2exe | |
opts['filename'] = 'frozen.log' | |
return opts | |
logging.basicConfig(**logging_options()) | |
def _get_instance_name(instance): | |
return instance.__class__.__module__ + "." + instance.__class__.__name__ + ".0x.." + hex(id(instance))[-2:] | |
class class_logger(object): | |
"""Class logger descriptor""" | |
def __init__(self): | |
self._logger = None | |
def __get__(self, instance, owner): | |
if self._logger is None: | |
self._logger = logging.getLogger(owner.__module__ + "." + owner.__name__) | |
return self._logger | |
class instance_logger(object): | |
"""Instance logger descriptor""" | |
def __init__(self): | |
self._logger = None | |
def __get__(self, instance, owner): | |
if self._logger is None: | |
self._logger = logging.getLogger(_get_instance_name(instance)) | |
return self._logger | |
def function_logger(): | |
"""Function auto-naming logger""" | |
global FUNC_LOGGERS | |
frame = sys._getframe(1) | |
mod = frame.f_globals['__name__'] | |
name = frame.f_code.co_name | |
logger_name = mod + '.' + name | |
if logger_name not in FUNC_LOGGERS: | |
FUNC_LOGGERS[logger_name] = logging.getLogger(logger_name) | |
return FUNC_LOGGERS[logger_name] | |
def module_logger(): | |
"""Module auto-naming logger""" | |
global MOD_LOGGERS | |
frame = sys._getframe(1) | |
mod = frame.f_globals['__name__'] | |
if mod not in MOD_LOGGERS: | |
MOD_LOGGERS[mod] = logging.getLogger(mod) | |
return MOD_LOGGERS[mod] | |
# provide public API of logging module | |
for name in dir(logging): | |
if not name.startswith('_'): | |
globals()[name] = getattr(logging, name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment