Search code examples
pythondjangologgingerror-loggingvalidationerror

Django logging - logging on ValidationError not working


So I want to be able to track any ValidationErrors being raised by the def clean method on a certain form. I have the a form called AdForm, the validation on the form does work, I can see the errors in the html output.

The logging also works since I get the logger info in the text file. The strange thing is, I get the notice;

2020-02-11 18:17:43,099 [INFO] .forms: AdForm is called

But I don't see the raised validation error in my log files?

Is there anything wrong with my settings? For some of you this might be piece of cake but I'm struggling to find my own errors, any help will be appreciated!

forms.py

from .models import Ad

import logging
logger = logging.getLogger(__name__)

class AdForm(forms.ModelForm)
    logger.info("AdForm is called")

    class Meta:
        model = Ad
        fields = [
            'title',
            'description'
        ]

    def clean(self):
        cleaned_date = super(AdForm, self).clean()
        title = cleaned_data.get('title')

        if len(title) < 4:
            logger.info("Title is shorter then 4 characters")
            raise forms.ValidationError("Title is too short")

        if len(title) > 24:
            logger.info("Title is shorter then 4 characters")
            raise forms.ValidationError("Title is too long")

settings.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
        },
    },
    'handlers': {
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': 'C:/Python/logs/mylog.log',
            'maxBytes': 1024*1024*5, #5mb
            'backupCount': 5,
            'formatter': 'standard',
        },
        'request_handler': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': 'C:/Python/logs/django_request.log',
            'maxBytes': 1024*1024*5, #5mb
            'backupCount': 5,
            'formatter': 'standard',
        },
    },
    'loggers': {
        '': {
            'handlers': ['default'],
            'level': 'DEBUG',
            'propagate': True
        },
        'django.request': {
            'handlers': ['request_handler'],
            'level': 'DEBUG',
            'propagate': False
        },
    }
}

Solution

  • Alright, found an issue within the logging settings;

    LOGGING = {
        'disable_existing_loggers': False, # Change this to False
    }
    

    This seems to do the trick!