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

Asked

Viewed 174 times

2

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

When I upgraded to Django 1.9, I started using the logging 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 into the specified file all the 500 errors, including the ones I didn’t explicitly pick. 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")

There is a simple way to log the date and time of the error, to be easier to correlate with the entry in access.log (where it is written something like "POST /meu/caminho HTTP/1.1" 500)? I imagine I have to touch formatters, but reading the documentation I didn’t understand very well how it works. The most important thing for me is the stack trace, of course, but this additional information would be very useful (if it is not possible, or is something more complicated, I can live without it - after all this type of error is relatively rare).

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

  • 1

    This might interest you to answer: http://answall.com/q/191784/101, I’ll delete it here.

2 answers

1


I tested here and 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', that verbose is formatted with the 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 Séntry to better organize errors, use the service getsentry.com, serves me well and is very easy to use, if I’m not mistaken allows up to 200 errors per day for free.

0

I took the data from this reply:

The official logging documentation is that one.

Examples:

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

Then you can take in the documentation the fields you want and assemble the log in the best way.

Updating:

That I used in a system of my own:

import logging

logging.basicConfig(filename='example.log',level=logging.DEBUG, filemode="w", format='%(asctime)s %(levelname)s: %(message)s')
  • In this question the author is creating a logger via code, to log things also via code (type: logger.error("mensagem")). In my case I’m setting a logger in the settings.py (sorry if this was not clear in the question), for Django himself to use. I saw in the Django documentation a similar example ('format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'), but I don’t quite understand what that means in the context of Django.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.