Python黑科技,教你学会Django系统错误监控

来源:http://www.jianshu.com/p/42e4287ffeda

话不多说,直入正题。

先上图,看一下监控的效果。

如下是监控我们网站系统错误的邮件。包含了请求的url地址,以及详细的异常信息。

 

一、监控所有的request请求

如何实现系统监控,自动发送错误日志的邮件呢?只需配置配置settings文件即可。

1.设置发送邮件配置信息

邮件会发送到ADMINS设定的邮件列表中。

SERVER_EMAIL ='[email protected]'
DEFAULT_FROM_EMAIL ='[email protected]'
ADMINS = (('receiver','[email protected]'),) EMAIL_HOST ='smtp.exmail.qq.com' EMAIL_HOST_USER ='[email protected]' EMAIL_HOST_PASSWORD ='123456' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

2.配置LOGGING

1)配置mail_admin的handler

level为日志级别

django.utils.log.AdminEmailHandler为django处理系统日志发送邮件的handler

在没有配置filter参数情况下,默认发送系统5XX状态的错误日志

'handlers': {
    'mail_admin': { 'level':'ERROR', 'class':'django.utils.log.AdminEmailHandler', 'include_html':False, } }

2)配置django.request模块的logger

将django的request模块配置如上的mail_admin handler

'loggers': {
    'django.request': { 'handlers': ['default','mail_admin'], 'propagate':True, 'level':'ERROR', }, }

二、监控非request请求

如何监控例如系统的定时任务等非用户发起的功能模块,我们可以自定义一个decorator来解决这个问题。

utils.send_exception_email(email_list,title,exc)为发送邮件的方法,可以自己实现,非常简单

def decorator_error_monitor(title):
    def wrap(f): def wrapped_f(*args, **kwargs): try: result = f(*args, **kwargs) return result except: exc = traceback.format_exc() utils.send_exception_email(email_list, title, exc) raise Exception(exc) return wrapped_f return wrap

对需要监控的方法使用decorator

@decorator_error_monitor("清算错误")
def do_settlement(users): for user in users: process_settlement_for_one_user(user)

监控效果如下图所示:

小结

以上监控方法,简单实用,无需开发额外的日志监控系统,可以在第一时间发现系统的问题,并得知系统的错误日志,帮助快速的定位问题。

猜你喜欢

转载自www.cnblogs.com/l520/p/10259969.html
今日推荐