1 import logging 2 3 def foo(s): 4 return 10 / int(s) 5 6 def bar(s): 7 return foo(s) * 2 8 9 def main(): 10 try: 11 bar(0) 12 except Exception as e: 13 logging.exception(e) 14 15 main() 16 print('所有的都执行完毕!') 17 18 ERROR:root:division by zero 19 Traceback (most recent call last): 20 File "57.py", line 11, in main 21 bar(0) 22 File "57.py", line 7, in bar 23 return foo(s) * 2 24 File "57.py", line 4, in foo 25 return 10 / int(s) 26 ZeroDivisionError: division by zero 27 所有的都执行完毕!#可以正常执行完毕程序并纪录错误
1 logger = logging.getLogger() 2 3 logfile = 'test.log' 4 hdlr = logging.FileHandler('sendlog.txt') 5 6 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') 7 8 hdlr.setFormatter(formatter) 9 10 logger.addHandler(hdlr) 11 12 logger.setLevel(logging.NOTSET)