django中使用日志输出

来源:互联网 发布:qr分解求逆矩阵 编辑:程序博客网 时间:2024/06/05 15:18

django中日志和国际化都是采用彼python的标准库来实现的,其中国际化是使用的GNU的gettext模块,日志采用的是logging模块。logging模块在日志方面是非常的强悍啊。

django的标准配置中有一个LOGGING的参数,但是并没有任何实现,在django.utils.log.py中给出了默认的实现方案,如下:

log.py

from __future__ import unicode_literalsimport loggingimport sysimport warnings# Imports kept for backwards-compatibility in Django 1.7.from logging import NullHandler  # NOQAfrom logging.config import dictConfig  # NOQAfrom django.conf import settingsfrom django.core import mailfrom django.core.mail import get_connectionfrom django.utils.deprecation import RemovedInNextVersionWarningfrom django.utils.encoding import force_textfrom django.utils.module_loading import import_stringfrom django.views.debug import ExceptionReporter, get_exception_reporter_filtergetLogger = logging.getLogger# Default logging for Django. This sends an email to the site admins on every# HTTP 500 error. Depending on DEBUG, all other log records are either sent to# the console (DEBUG=True) or discarded by mean of the NullHandler (DEBUG=False).DEFAULT_LOGGING = {    'version': 1,    'disable_existing_loggers': False,    'filters': {        'require_debug_false': {            '()': 'django.utils.log.RequireDebugFalse',        },        'require_debug_true': {            '()': 'django.utils.log.RequireDebugTrue',        },    },    'handlers': {        'console': {            'level': 'INFO',            'filters': ['require_debug_true'],            'class': 'logging.StreamHandler',        },        'null': {            'class': 'logging.NullHandler',        },        'mail_admins': {            'level': 'ERROR',            'filters': ['require_debug_false'],            'class': 'django.utils.log.AdminEmailHandler'        }    },    'loggers': {        'django': {            'handlers': ['console'],        },        'django.request': {            'handlers': ['mail_admins'],            'level': 'ERROR',            'propagate': False,        },        'django.security': {            'handlers': ['mail_admins'],            'level': 'ERROR',            'propagate': False,        },        'py.warnings': {            'handlers': ['console'],        },    }}


因为django的调试服务器默认开启了自动加载,所有直接使用print是无法打印输出的,(服务器的启动是创建的子进程),否则只能每次修改后重启服务器,如果不想每次重启服务器的话,就需要自己来配置LOGGING选项。


如下是我根据django中默认的配置修改后来进行使用的方案,我从log.py中导入了DEFALUT_LOGGING如下:

LOGGING = DEFAULT_LOGGINGLOGGING['formatters']={        'standard': {                'format': '%(levelname)s %(asctime)s %(message)s'                },}LOGGING['handlers']['console']['formatter']='standard'
在使用的时候,直接使用默认日志器django,如下示例代码:
#coding=utf-8
<pre name="code" class="python">from django.shortcuts import renderfrom django.http import HttpResponseimport loggingfrom django.utils.log import getLogger# Create your views here."""不要相信任何用户提交数据,对于用户提交数据请一定做转义处理,否则直接字符串序列化可能会导致被执行(1)在html中以javascript被执行(2)在数据库中以数据库语句被执行"""logger = logging.getLogger("django")#logger = getLogger()def show_your_name(request):name = request.GET["name"] if "name" in request.GET else "defalut-django"logger.warn("name=%s" % (name,))return render(request, "safty/show_name.html", locals())




1 0
原创粉丝点击