Ticket #12012: 12012-r11603.diff

File 12012-r11603.diff, 8.1 KB (added by simon, 15 years ago)
  • django/__init__.py

    diff --git a/django/__init__.py b/django/__init__.py
    index 2b87a7e..b92c1f4 100644
    a b  
     1from django.utils import log
     2
    13VERSION = (1, 2, 0, 'alpha', 0)
    24
    35def get_version():
  • django/conf/__init__.py

    diff --git a/django/conf/__init__.py b/django/conf/__init__.py
    index 7bc7ae9..793c721 100644
    a b class Settings(object):  
    108108            os.environ['TZ'] = self.TIME_ZONE
    109109            time.tzset()
    110110
     111        if getattr(self, 'LOGGING', None):
     112            from django.utils import log
     113            log.configure_from_dict(self.LOGGING)
     114
    111115    def get_all_members(self):
    112116        return dir(self)
    113117
  • django/core/management/commands/runserver.py

    diff --git a/django/core/management/commands/runserver.py b/django/core/management/commands/runserver.py
    index fc2c694..78798f1 100644
    a b class Command(BaseCommand):  
    99            help='Tells Django to NOT use the auto-reloader.'),
    1010        make_option('--adminmedia', dest='admin_media_path', default='',
    1111            help='Specifies the directory from which to serve admin media.'),
     12        make_option('--loglevel', dest='log_levels', action='append',
     13            help='Set the minimum log level to be displayed at the console'),
    1214    )
    1315    help = "Starts a lightweight Web server for development."
    1416    args = '[optional port number, or ipaddr:port]'
    class Command(BaseCommand):  
    3941        use_reloader = options.get('use_reloader', True)
    4042        admin_media_path = options.get('admin_media_path', '')
    4143        shutdown_message = options.get('shutdown_message', '')
     44        log_levels = options.get('log_levels', [])
    4245        quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'
    4346
     47        if log_levels:
     48            from django.utils.log import logger as django_logger
     49            import logging
     50            django_logger.addHandler(logging.StreamHandler())
     51            for log_level in log_levels:
     52                try:
     53                    log_name, level = log_level.split(':')
     54                except ValueError:
     55                    raise CommandError("Invalid log level specified")
     56                if level.isdigit():
     57                    level = int(level)
     58                else:
     59                    level = getattr(logging, level.upper(), None)
     60                    if level is None:
     61                        raise CommandError("Invalid log level: %s" % level)
     62                logging.getLogger(log_name).setLevel(level)
     63
    4464        def inner_run():
    4565            from django.conf import settings
    4666            from django.utils import translation
     67
    4768            print "Validating models..."
    4869            self.validate(display_num_errors=True)
    4970            print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)
  • django/db/backends/__init__.py

    diff --git a/django/db/backends/__init__.py b/django/db/backends/__init__.py
    index 9a1fe30..a183941 100644
    a b class BaseDatabaseWrapper(local):  
    8181        cursor = self._cursor()
    8282        if settings.DEBUG:
    8383            return self.make_debug_cursor(cursor)
    84         return cursor
     84        return self.make_logging_cursor(cursor)
    8585
    8686    def make_debug_cursor(self, cursor):
    8787        return util.CursorDebugWrapper(cursor, self)
    8888
     89    def make_logging_cursor(self, cursor):
     90        return util.CursorLoggingWrapper(cursor, self)
     91
    8992class BaseDatabaseFeatures(object):
    9093    allows_group_by_pk = False
    9194    # True if django.db.backend.utils.typecast_timestamp is used on values
  • django/db/backends/util.py

    diff --git a/django/db/backends/util.py b/django/db/backends/util.py
    index f9c07a9..ca0043a 100644
    a b  
    11import datetime
    22from time import time
    3 
    43from django.utils.hashcompat import md5_constructor
     4import logging
     5logger = logging.getLogger('django.db.sql')
    56
    67try:
    78    import decimal
    89except ImportError:
    910    from django.utils import _decimal as decimal    # for Python 2.3
    1011
    11 class CursorDebugWrapper(object):
     12class CursorWrapper(object):
     13    def __init__(self, cursor, db):
     14        self.cursor = cursor
     15        self.db = db # Instance of a BaseDatabaseWrapper subclass
     16
     17    def __getattr__(self, attr):
     18        if attr in self.__dict__:
     19            return self.__dict__[attr]
     20        else:
     21            return getattr(self.cursor, attr)
     22
     23    def __iter__(self):
     24        return iter(self.cursor)
     25
     26class CursorLoggingWrapper(CursorWrapper):
     27    def execute(self, sql, params=()):
     28        start = time()
     29        try:
     30            return self.cursor.execute(sql, params)
     31        finally:
     32            stop = time()
     33            sql = self.db.ops.last_executed_query(self.cursor, sql, params)
     34            logger.info('%.3fs:\t%s' % (stop - start, sql))
     35
     36    def executemany(self, sql, param_list):
     37        start = time()
     38        try:
     39            return self.cursor.executemany(sql, param_list)
     40        finally:
     41            stop = time()
     42            logger.info('%.3fs:\t%s' % (stop - start, sql))
     43
     44class CursorDebugWrapper(CursorWrapper):
    1245    def __init__(self, cursor, db):
    1346        self.cursor = cursor
    1447        self.db = db # Instance of a BaseDatabaseWrapper subclass
    class CursorDebugWrapper(object):  
    2457                'sql': sql,
    2558                'time': "%.3f" % (stop - start),
    2659            })
     60            logger.info('%.3fs:\t%s' % (stop - start, sql))
    2761
    2862    def executemany(self, sql, param_list):
    2963        start = time()
    class CursorDebugWrapper(object):  
    3569                'sql': '%s times: %s' % (len(param_list), sql),
    3670                'time': "%.3f" % (stop - start),
    3771            })
    38 
    39     def __getattr__(self, attr):
    40         if attr in self.__dict__:
    41             return self.__dict__[attr]
    42         else:
    43             return getattr(self.cursor, attr)
    44 
    45     def __iter__(self):
    46         return iter(self.cursor)
     72            logger.info('%.3fs:\t%s' % (stop - start, sql))
    4773
    4874###############################################
    4975# Converters from database (string) to Python #
  • new file django/utils/log.py

    diff --git a/django/utils/log.py b/django/utils/log.py
    new file mode 100644
    index 0000000..21fd0aa
    - +  
     1from django.utils.importlib import import_module
     2from django.core.exceptions import ImproperlyConfigured
     3import logging
     4
     5class NullHandler(logging.Handler):
     6    def emit(self, record):
     7        pass
     8
     9logger = logging.getLogger('django')
     10logger.setLevel(logging.INFO)
     11if len(logger.handlers) == 0:
     12    logger.addHandler(NullHandler())
     13logger.propagate = False
     14
     15def configure_from_dict(configuration):
     16    "Configure loggers using a settings.LOGGING style dictionary"
     17    for logger_label, config in configuration.items():
     18        logger = logging.getLogger(logger_label)
     19        level = config.pop('level', None)
     20        if level is not None:
     21            if level.isdigit():
     22                level_int = int(level)
     23            else:
     24                level_int = getattr(logging, level.upper(), None)
     25                if level_int is None:
     26                    raise ImproperlyConfigured, \
     27                        '"%s" is not a valid logging level' % level
     28            logger.setLevel(level_int)
     29        handler = config.pop('handler', None)
     30        if handler is not None:
     31            klass = handler_from_string(handler)
     32            logger.addHandler(klass(**config))
     33
     34def handler_from_string(string):
     35    # Could refactor with django.core.handlers.base.BaseHandler.load_middleware
     36    try:
     37        dot = string.rindex('.')
     38    except ValueError:
     39        raise ImproperlyConfigured, '%s isn\'t a handler module' % string
     40    module, classname = string[:dot], string[dot+1:]
     41    try:
     42        mod = import_module(module)
     43    except ImportError, e:
     44        raise ImproperlyConfigured, 'Error importing handler %s: "%s"' % (module, e)
     45    try:
     46        klass = getattr(mod, classname)
     47    except AttributeError:
     48        raise ImproperlyConfigured, 'Module "%s" does not define a "%s" class' % (module, classname)
     49    return klass
Back to Top