如何在Django中记录文件

时间:2017-08-16 07:43:58

标签: python django

我在views.py中有这个功能(与联系表格有关)。我需要将所有输入和输出记录到临时文件中,但我不知道如何在django中执行此操作。出现一个新错误:无法找到记录器“farah”的处理程序

Settings.py:

LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
    'farah': {
        'level': 'DEBUG',
        'class': 'logging.FileHandler',
        'filename': '/home/farah/update/farah.log',
    },
},
'loggers': {
    'django': {
        'handlers': ['farah'],
        'level': 'DEBUG',
        'propagate': True,
    },
},
}

views.py中的函数:     logger = logging.getLogger('farah')     def contact(request):

form = FeedbackForm(request.POST or None)


if form.is_valid():

        recaptcha_response = request.POST.get('g-recaptcha-response')
        url = 'https://www.google.com/recaptcha/api/siteverify'
        values = {
            'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
            'response': recaptcha_response
        }
        data = urllib.urlencode(values).encode()
        req =  urllib2.Request(url, data=data)
        response = urllib2.urlopen(req)
        result = json.loads(response.read().decode())
        ''' End reCAPTCHA validation '''

        if result['success']:
    form.save()
    message = u'You have feedback\nName: %s\nEmail: %s\nPhone: %s\nCountry: %s\nFeedback:\n%s' % (
        self.cleaned_data.get['name'],
        self.cleaned_data.get['email'],
        self.cleaned_data.get['phone'],
        self.cleaned_data.get['country'],
        self.cleaned_data.get['feedback'])
    try:
        send_mail('NEW FEEDBACK', message, '', settings.DEFAULT_FROM_EMAIL) # to admin
        send_mail('THANK YOU for contacting us', 'We will be back to you promptly.', '', [self.cleaned_data.get['email'],]) # to user
        messages.info(request, 'SUCCESS! Your message has been sent!')
        form = FeedbackForm()
    except:
        messages.info(request, 'Sorry, can\'t send feedback right now.')
        else:
            messages.error(request, 'Invalid reCAPTCHA. Please try again.')


    else:
      form = FeedbackForm()
      logger.error('Log whatever you want') 



return render(request, 'contact.html', {'active_page':'contact','form': form,})

我在谷歌上看过这个页面,但我不知道该怎么做:

https://docs.python.org/2.3/lib/node304.html

2 个答案:

答案 0 :(得分:2)

重要的是要在Logger中插入要记录的Django应用的名称。例如:如果您在django项目中的应用程序被称为“鼠标”,并且您想将应用程序中发生的事情登录到“文件”处理程序,则记录器应如下所示:

'loggers': {
    'mouse': {
        'handlers': ['file'], 
        'level': 'DEBUG',
        'propagate': True,
    },

答案 1 :(得分:1)

在settings.py中添加日志记录配置 *

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/path/to/django/debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

*

在Views.py中添加以下代码

import logging
logger = logging.getLogger(__name__)
def contact(request):
    ...
    logger.debug('Log whatever you want')
    # It will we logged in '/path/to/django/debug.log' the path you have specified in settings.py logging conf