Django我们如何使用app name目录和todaydate.log文件生成app wise日志

时间:2016-01-20 21:36:43

标签: python django

Django:我们如何使用app name目录生成app wise登录     我需要生成应用程序明智的log.Ex.     1:var / app1 / todaydate.log     2:var / app2 / todaydate.log

1 个答案:

答案 0 :(得分:2)

import os
import datetime

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
]

MY_APPS = [
    'accounts'
]

INSTALLED_APPS += MY_APPS

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
    },
    'loggers': {
    }
}

MY_LOGGERS = {}
MY_HANDLERS = {}
for app in MY_APPS:
    directory = os.path.dirname(os.path.dirname(__file__)) + "/var/log/" + app + "/"
    if not os.path.exists(directory):
        os.makedirs(directory)

    MY_HANDLERS[app] = {
        'level': 'DEBUG',
        'class': 'logging.handlers.RotatingFileHandler',
        'filename': directory + '/' + str(datetime.date.today()) + '.log',
        'maxBytes': 1024*1024*5,
        'backupCount': 5,
        'formatter': 'verbose'
    }

    MY_LOGGERS[app] = {
        'handlers': [app],
        'level': 'DEBUG',
        'propagate': True,
    }
LOGGING['handlers'].update(MY_HANDLERS)
LOGGING['loggers'].update(MY_LOGGERS)