Django日誌記錄詳細的報錯信息

當服務器500錯誤的時候,普通日誌只會記錄一行500的request信息,並不會記錄詳細的報錯定位python

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

須要添加一個在日誌中記錄詳細錯誤信息的middlewaredjango

# -*- 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())

將此中間件添加到settings的MIDDLEWARE_CLASSES中api

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

使用Django logger服務器

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

效果app

[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
相關文章
相關標籤/搜索