how to log a file in Django

Viewed 19921

I have this function in views.py ( related to contact form). I need to log all the inputs and output to a temporary file, but I don't know how to do it in django. A new error appears : No handlers could be found for logger "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,
        },
    },
}

The function in 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,})

I viewed this page on google, but I don't know how to do it :

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

2 Answers

What is relevant is to insert in the Loggers, the name of your Django App that you want to log. For instance: if your app, inside your django project, is called "mouse" and you want to log to the "file" handler what is going on in the app, the logger should be like this:

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