[Fixed]-Django logging requests

16👍

Django logger extensions work differently in development than in production (settings.DEBUG=True|False).

What you expect to see – http request logs – are written by django.server logger,
which is active only in development server (runserver command).

I see that in your configuration you use django.request logger. This logger name is very confusing – because as its name suggest – users will expect it to log all http requests – but it won’t.

django.request will log only 4xx and 5xx requests.

I’ve made a screencast which explain this issue in detail.

Django documentation about loggers.

8👍

demo of logging in django,log is location in /path/to/your/project/log/info.log,
your need to create info.log in log/ dir first.

settings.py

LOG_PATH = os.path.join(BASE_DIR, "log/")
LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format': '%(asctime)s [%(levelname)s]- %(message)s'}

    },
    'handlers': {
        'django_error': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': LOG_PATH + 'django.log',
            'formatter': 'standard'
        },
        'info': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': LOG_PATH + 'info.log',
            'formatter': 'standard'
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'standard'
        }
    },
    'loggers': {
        'info': {
            'handlers': ['info', "console"],
            'level': 'DEBUG',
            'propagate': True
        },
        'django': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': True,
        },
        'django.request': {
            'handlers': ['django_error', 'console'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'django.db.backends': {
            'handlers': ['console'],
            'level': 'ERROR',
            'propagate': True,
        }
    },
}

the effect of loggers is:

  • info: your custom debug info
  • django: the request record
  • django.request: the error request
  • django.db.backends:Messages
    relating to the interaction of code with the database

more info here

views.py

import logging
logger = logging.getLogger("info")
logger.info('something')

you will get

2017-08-31 13:05:40,492 [INFO]- something

in log/info.log later.

👤Ykh

Leave a comment