zoukankan      html  css  js  c++  java
  • Python traceback 模块, 打印异常信息

    Python感觉是模仿Java, 到处都需要加try..catch...。

    这里记录一下用法,方便后续使用。

     1 # -*- coding:utf-8 -*-
     2 
     3 import os
     4 import logging
     5 import traceback
     6 
     7 #设置log, 这里使用默认log
     8 logging.basicConfig(
     9         level=logging.INFO,
    10         format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    11         datefmt='[%Y-%m_%d %H:%M:%S]',
    12         filename=os.path.dirname(os.path.realpath(__file__)) + "/" + 'test.log',
    13         filemode='a')
    14 
    15 a=10
    16 b=0 #设置为0, 走异常流程; 否则, 走正常流程
    17 
    18 try:
    19     res=a/b
    20     logging.info("exec success, res:" + str(res))
    21 except Exception,e:
    22     #format_exc()返回字符串,print_exc()则直接给打印出来
    23     traceback.print_exc()
    24     logging.warning("exec failed, failed msg:" + traceback.format_exc())

    logging默认打印级别是warning.

    format_exc()返回字符串,print_exc()则直接给打印出来

    日志打印:

    [2017-11_17 07:51:02] trace.py[line:24] WARNING exec failed, failed msg:Traceback (most recent call last):
      File "trace.py", line 19, in <module>
        res=a/b
    ZeroDivisionError: integer division or modulo by zero
    
  • 相关阅读:
    程序员修炼之道:从小工到专家
    2020.12.16收获
    2020.12.15收获
    2020.12.14收获
    2020.12.13收获
    Android学习第二天——对Android的简单了解
    Java学习12.18
    考试加分项
    Java学习12.17
    Java建议
  • 原文地址:https://www.cnblogs.com/xudong-bupt/p/7849487.html
Copyright © 2011-2022 走看看