2014-08-25

Django logging setting, part 2

This is a follow up to the Django logging setting post in 2013.
This time, it makes use of the hierarchical nature of the logging system, removing the need to define a separate section for each app in the settings file. Notice the dot after the <project_name> in U_LOGGER_ROOT.
=== settings.py ===

U_LOGFILE_NAME = r'/path/to/log.txt'
U_LOGFILE_SIZE = 1 * 1024 * 1024
U_LOGFILE_COUNT = 2
U_LOGGER_ROOT = '<project_name>.'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
        },
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'logfile': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': U_LOGFILE_NAME,
            'maxBytes': U_LOGFILE_SIZE,
            'backupCount': U_LOGFILE_COUNT,
            'formatter': 'standard',
        },
    },
    'loggers': {
        U_LOGGER_ROOT.rstrip('.'): {
            'handlers': ['logfile'],
            'level': 'DEBUG',
            'propagate': True,
        },
    }
}

=== in any app module ===

import logging
from  import settings

logger = logging.getLogger(settings.U_LOGGER_ROOT + __name__)
logger.info('some useful information')

No comments: