5分鐘教你學會Django系統錯誤監控
阿新 • • 發佈:2018-06-20
使用 推薦 gin 資料 tps 發現 ror python開發 包括
將django的request模塊配置如上的mail_admin handler
一、監控所有的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
‘loggers‘: {
‘django.request‘: {
‘handlers‘: [‘default‘,‘mail_admin‘],
‘propagate‘:True,
‘level‘:‘ERROR‘,
},
}
在這裏還是要推薦下我自己建的Python開發學習群:725479218,群裏都是學Python開發的,如果你正在學習Python ,小編歡迎你加入,大家都是軟件開發黨,不定期分享幹貨(只有Python軟件開發相關的),包括我自己整理的一份2018最新的Python進階資料和高級開發教程,歡迎進階中和進想深入Python的小夥伴
二、監控非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)
效果如下
以上監控方法,簡單實用,無需開發額外的日誌監控系統,可以在第一時間發現系統的問題,並得知系統的錯誤日誌,幫助快速的定位問題。
5分鐘教你學會Django系統錯誤監控