14

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

1

3 Answers 3

19

Add logging configurations in 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,
        },
    },
}

In views.py add the following code:

import logging
logger = logging.getLogger(__name__)
def contact(request):
    ...
    logger.debug('Log whatever you want')
    # It will be logged in '/path/to/django/debug.log' the path you have specified in settings.py logging conf
Sign up to request clarification or add additional context in comments.

6 Comments

LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'farah.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, }
else: #form = FeedbackForm() logger.debug('Log whatever you want')
The file farah.log dont show the message for logger.debug
@user8427236 please provide full path of log file
If you leave the type of loggers blank, every module will propagate. In other words, in this example change 'django': to ' ': (yes, blank).
|
3

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,
    },

Comments

0

I separated different types of logs into different files

LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
    # Handler for all log messages
    'file_all': {
        'level': 'DEBUG',
        'class': 'logging.FileHandler',
        'filename': 'debug/all.log',
    },
    # Handler for warnings and errors
    'file_warnings_errors': {
        'level': 'WARNING',
        'class': 'logging.FileHandler',
        'filename': 'debug/warnings_errors.log',
    },
},
'loggers': {
    'django': {
        # Both handlers: one for all messages and another for warnings/errors
        'handlers': ['file_all', 'file_warnings_errors'],
        'level': 'DEBUG',
        'propagate': True,
    },
},

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.