python 上下文處理錯誤,記錄日誌

來源:互聯網
上載者:User

標籤:管理器   sel   except   str   roc   add   ini   error   pytho   

之前發過了裝飾器版本的異常記錄日誌,但是需要裝飾在函數或方法上。此篇用上下文管理,用一個with就能記錄錯誤了,不需要寫成函數。

 

import traceback
# pip install multiprocessing_log_manager
from multiprocessing_log_manager import LogManagerclass ExceptionContextManager(): """ 用上下文管理器計時,可對程式碼片段進行錯誤捕捉,比裝飾器更細膩 """ def __init__(self, logger_name=‘ExceptionContextManager‘, verbose=100, donot_raise__exception=True, ): """ :param _verbose: 列印錯誤的深度,對應traceback對象的limit,為正整數 :param donot_raise__exception:是否不重新拋出錯誤,為Fasle則拋出,為True則不拋出 """ self.logger = LogManager(logger_name).get_logger_and_add_handlers() self._verbose = verbose self._donot_raise__exception = donot_raise__exception def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): # print(exc_val) # print(traceback.format_exc()) exc_str = str(exc_type) + ‘ : ‘ + str(exc_val) exc_str_color = ‘\033[0;30;45m%s\033[0m‘ % exc_str if self._donot_raise__exception: self.logger.error(‘\n‘.join(traceback.format_tb(exc_tb)[:self._verbose]) + exc_str_color) return self._donot_raise__exception # __exit__方法必須retuen True才會不重新拋出錯誤if __name__ == ‘__main__‘: def f1(): 1 + ‘2‘ def f2(): f1() def f3(): f2() def f4(): f3() def run(): f4()

 

運行結果是這樣:

 

python 上下文處理錯誤,記錄日誌

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.