1.抛出异常
2.取得反向跟踪信息
3.断言
4.使用日志
5.IDE调试器-断点及逐行跟踪等

抛出异常 raise Exception 与 try except 的配合使用

def boxPrint(symbol,width,height):
    if len(symbol) != 1:
        raise Exception('Symbol must be a single character string.')
    if width <= 2:
        raise Exception('Width must be greater than 2.')
    if height <= 2:
        raise Exception('Height must be greater than 2.')
    print(symbol * width)
    for i in range(height-2):
        print(symbol + (' '*(width-2)) + symbol)
        i = i + 1
    print(symbol * width)

for sym,w,h in (('*',4,4),('0',20,5),('x',1,3),('zz',3,3)):
    try:
        boxPrint(sym,w,h)
    except Exception as err:
        print('An exception happened: '+str(err))

断言 assert

断言针对的是程序员的错误,而不是用户的错误。对于业务逻辑层面的错误处理,要抛出异常,而不是用断言语句来检测

market_2nd = {'ns':'green','ew':'red'}          # Market街和第2街的路口,南北向和东西向的交通灯分别为绿色和红色
misson_16th = {'ns':'red','ew':'green'}
def switchLights(stoplight):
    for key in stoplight.keys():
        if stoplight[key] == 'green':
            stoplight[key] = 'yellow'
        if stoplight[key] == 'yellow':
            stoplight[key] = 'red'
        if stoplight[key] == 'red':
            stoplight[key] = 'green'
    assert 'red' in stoplight.values(), 'Neither light is red! '+str(stoplight)    # 都不是红灯通过断言报错
switchLights(market_2nd)

assert 用来调试程序,调试通过后,可以跳过断言来执行
如上面这段代码, python assertlight.py 执行到都不是红灯时,会报错,检测出了会撞车的逻辑异常
python -O assertlight.py 取消执行断言代码,不会报错。在排除了程序中的逻辑异常后取消执行断言

使用 traceback.format_exc() 获取反向跟踪信息

import traceback
try:
    raise Exception('This is the error message.')
except:
    errorFile = open('errorInfo.txt','w')
    errorFile.write(traceback.format_exc())
    errorFile.close()
    print('The traceback info was written to errorInfo.txt.')

日志方式

# 日志 logging模块
import logging
logging.basicConfig(level = logging.DEBUG,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")
# 日志写入文件
import logging

logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")
# 日志输出到控制台以及文件
import logging

logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.INFO)

logger.addHandler(handler)
logger.addHandler(console)

logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")

也可添加如下:

logger.add(os.path.join(BASE_DIR, 'Log', "{time:YYYY-MM-DD}.log"),
           format="{time:YYYY-MM-DD at HH:mm:ss} - {level} - {message}", rotation="00:00", enqueue=True, level="DEBUG")

更多日志使用方法

不要害怕告别,要相信,四季更替,花开花落,都是命中注定。