在实际的生产使用中,常常需要使用日志配合异常捕获来监测程序的运行情况。本文对python中的Logging模块和traceback模块的使用做简单的总结,以便快速上手。

1.日志模块(logging)

python的logging模块可分别对日志级别、日志输出格式、日期输出格式,日志路径,打开文件方式等进行设置。

basicConfig关键字参数

(1) level

(2) format

(3) datefmt

参考time.strftime

2.异常捕获模块(traceback)

  • traceback.format_exc()以字符串返回异常信息
  • traceback.print_exc()直接打印出异常信息
    可以填入file参数,把异常信息填入到指定的file里
    traceback.print_exc(file=open('error.txt','a'))

3.代码示例

# -*- coding:utf-8 -*-

import os
import logging
import traceback

#设置log, 这里使用默认log
logging.basicConfig(
    level=logging.INFO,                                                            #日志级别,只有日志级别大于等于设置级别的日志才会输出
    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',  #日志输出格式
    datefmt='[%Y-%m_%d %H:%M:%S]',                                                 # 日期表示格式
    filename=os.path.dirname(os.path.realpath(__file__)) + "/" + 'test.log',       #输出定向的日志文件路径
    filemode='a'                                                                   #日志写模式,是否尾部添加还是覆盖
    )

a=10
b=0 #设置为0, 走异常流程; 否则, 走正常流程

try:
  res=a/b
  logging.info("exec success, res:" + str(res))
except Exception,e:
  #format_exc()返回异常信息字符串,print_exc()则直接给打印异常信息
  traceback.print_exc()
  logging.warning("exec failed, failed msg:" + traceback.format_exc())

参考链接

日志模块教程
异常捕获教程

01-07 13:05