How to write the date and time of an error in the Django log?

2

I started a project in Django 1.4, and every mistake I made via try..except I printed in sys.stderr - making it fall into the same Apache log file (error.log). It worked, but only for the errors that I explicitly took, and in addition the errors of all running instances went to the same file. But the advantage is that Apache prefixed all errors with the date and time of the error.

When I upgraded to Django 1.9, I started using the logging system based on in this first example (in settings.py):

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'ERROR',
            'class': 'logging.FileHandler',
            'filename': '/var/www/vhosts/example.com/statistics/logs/django_errors.log',
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['file'],
            'level': 'ERROR',
            'propagate': True,
        },
    },
}

And he went on to log all 500 errors in the specified file, including those that I did not explicitly catch. The only problem is that it only logs the error itself, gives no indication of the date and time of the error, nor any additional information:

Internal Server Error: /admin/example/projeto/add/
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 132, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py", line 618, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  ...
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 205, in execute
    self.errorhandler(self, exc, value)
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
IntegrityError: (1048, "Column 'area' cannot be null")

Is there a simple way to log the date and time of the error, to make it easier to correlate with the entry in access.log (where something like "POST /meu/caminho HTTP/1.1" 500 is written)? I imagine I have to fiddle with formatters , but reading the documentation I do not quite understand how it works. Most important to me is the stack trace , of course, but this additional information would be very useful (if it is not possible, or it's something more complicated, I can live without it - after all this kind of error is relatively rare).

P.S. I'm using mod_wsgi, if this is of any relevance.

    
asked by anonymous 03.10.2016 / 20:28

2 answers

1

I tried here and it really was not showing the date and time, but just indicate the format of the log that worked, in this case I put formatter: 'verbose' , this verbose is formatted with date:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt': "%d/%b/%Y %H:%M:%S"
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '{0}/errors.log'.format(BASE_DIR),
            'formatter': 'verbose'  # aqui você indica o formato definido em formatters
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

I currently use sentry to better organize errors, I use the getsentry.com service, it caters well and is very easy to use, if not I'm mistakenly allowing up to 200 errors per day for free.

    
05.10.2016 / 19:38
0

I've taken the data from this response :

The official logging documentation is this .

Examples:

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
                              "%Y-%m-%d %H:%M:%S")

Then you can get the fields you want and set up the log in the best way.

Updating:

This one I used on my system:

import logging

logging.basicConfig(filename='example.log',level=logging.DEBUG, filemode="w", format='%(asctime)s %(levelname)s: %(message)s')
    
03.10.2016 / 20:35