您的位置:首页 > 编程语言 > Go语言

django中使用日志输出

2015-12-22 21:30 190 查看
django中日志和国际化都是采用彼python的标准库来实现的,其中国际化是使用的GNU的gettext模块,日志采用的是logging模块。logging模块在日志方面是非常的强悍啊。django的标准配置中有一个LOGGING的参数,但是并没有任何实现,在django.utils.log.py中给出了默认的实现方案,如下:log.py
from __future__ import unicode_literals

import logging
import sys
import warnings
# Imports kept for backwards-compatibility in Django 1.7.
from logging import NullHandler  # NOQA
from logging.config import dictConfig  # NOQA

from django.conf import settings
from django.core import mail
from django.core.mail import get_connection
from django.utils.deprecation import RemovedInNextVersionWarning
from django.utils.encoding import force_text
from django.utils.module_loading import import_string
from django.views.debug import ExceptionReporter, get_exception_reporter_filter

getLogger = 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_LOGGING
LOGGING['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())

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: