django全局异常捕获保存和输出,logger配置

Middleware

1
2
3
4
5
6
7
8
9
# -*- 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

1
2
3
MIDDLEWARE_CLASSES = (
'sql.exception_logging_middleware.ExceptionLoggingMiddleware',
)

logger

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
DEFAULT_LOGS = '/tmp/default.log'
stamdard_format = '[%(asctime)s][%(threadName)s:%(thread)d]' + \
'[task_id:%(name)s][%(filename)s:%(lineno)d] ' + \
'[%(levelname)s]- %(message)s'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': { # 详细
'format': stamdard_format
},
},
'handlers': {
'default': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': DEFAULT_LOGS,
'maxBytes': 1024 * 1024 * 100, # 5 MB
'backupCount': 5,
'formatter': 'standard',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
}
},
'loggers': {
'default': { # default日志,存放于log中
'handlers': ['default'],
'level': 'DEBUG',
},
'django.db': { # 打印SQL语句到console,方便开发
'handlers': ['console'],
'level': 'DEBUG',
'propagate': True,
},
'django.request': { # 打印错误信息到console,方便开发
'handlers': ['console'],
'level': 'DEBUG',
'propagate': True,
},
}
}

log文件

1
2
3
4
5
6
7
8
[2018-04-16 10:33:02,639][MainThread:139636491347776][task_id:default][exception_logging_middleware.py:10] [ERROR]- Traceback (most recent call last):
File "/opt/venv4archer/lib/python3.4/site-packages/django/core/handlers/base.py", line 132, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/opt/venv4archer/lib/python3.4/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/opt/archer/sql/views_ajax.py", line 340, in getOscPercent
return HttpResponse(json.dumps(pctResult), content_type='application/json')
UnboundLocalError: local variable 'pctResult' referenced before assignment