Django logs detailed error reporting information

When the server 500 makes an error, the ordinary log will only record the request information of 500 in one line, and will not record the detailed error location

[ERROR] 2019-06-12 15:07:03,597 "GET /api/v1/test/ HTTP/1.1" 500 74196

You need to add a middleware that records detailed error information in the log

# -*- coding: UTF-8 -*-
import logging

logger = logging.getLogger('default')


class ExceptionLoggingMiddleware(object):
    def process_exception(self, request, exception):
        import traceback
        logger.error(traceback.format_exc())

Add this middleware to the midview of settings_In classes

MIDDLEWARE_CLASSES = (
'utils.my_middleware.ExceptionLoggingMiddleware',
)

Use Django logger

    'loggers': {
        'django': {
            'handlers': ['file', 'console'],
            'level': 'INFO'
        },

Effect

[ERROR] 2019-06-12 15:07:02,265 Internal Server Error: /api/v1/test/
Traceback (most recent call last):
  File "E:\tcp_check\venv\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
    response = get_response(request)
  File "E:\tcp_check\venv\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "E:\tcp_check\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\tcp_check\tcp_test_app\views.py", line 23, in test
    a=1/0
ZeroDivisionError: division by zero
[ERROR] 2019-06-12 15:07:03,597 "GET /api/v1/test/ HTTP/1.1" 500 74196

 

Similar Posts: