Python中使用logging和traceback模块记录日志和跟踪异常

yipeiwu_com6年前Python基础

logging模块

logging模块用于输出运行日志,可以设置不同的日志等级,保存信息到日志文件中等。 相比print,logging可以设置日志的等级,控制在发布版本中的输出内容,并且可以指定日志的输出格式。

1. 使用logging在终端输出日志

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging # 引入logging模块
# 设置打印日志级别 CRITICAL > ERROR > WARNING > INFO > DEBUG
logging.basicConfig(level = logging.DEBUG,format = '%(asctime)s - %(name)s
 -%(filename)s[line:%(lineno)d] - %(levelname)s - %(message)s')
# 将信息打印到控制台上
logging.debug(u"调试")
logging.info(u"执行打印功能")
logging.warning(u"警告")
logging.error(u"错误")
logging.critical(u"致命错误")

输出

2. 使用logging在終端輸出日志,並保存日志到本地log文件

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging # 引入logging模块
import os.path
# 第一步,创建一个logger
logger = logging.getLogger()
logger.setLevel(logging.DEBUG) # Log等级开关
# 第二步,创建一个handler,用于写入日志文件
log_path = os.path.dirname(os.getcwd()) + '/Logs/'
log_name = log_path + 'log.log'
logfile = log_name
file_handler = logging.FileHandler(logfile, mode='a+')
file_handler.setLevel(logging.ERROR) # 输出到file的log等级的开关
# 第三步,定义handler的输出格式
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
file_handler.setFormatter(formatter)
# 第四步,将handler添加到logger里面
logger.addHandler(file_handler)
# 如果需要同時需要在終端上輸出,定義一個streamHandler
print_handler = logging.StreamHandler() # 往屏幕上输出
print_handler.setFormatter(formatter) # 设置屏幕上显示的格式
logger.addHandler(print_handler)
# 日志信息
logger.debug('this is a logger debug message')
logger.info('this is a logger info message')
logger.warning('this is a logger warning message')
logger.error('this is a logger error message')
logger.critical('this is a logger critical message')
# 或使用logging
logging.debug('this is a logger debug message')
logging.info('this is a logger info message')
logging.warning('this is a logger warning message')
logging.error('this is a logger error message')
logging.critical('this is a logger critical message')

日志等级划分

  • FATAL:致命错误
  • CRITICAL:特别糟糕的事情,如内存耗尽、磁盘空间为空,一般很少使用
  • ERROR:发生错误时,如IO操作失败或者连接问题
  • WARNING:发生很重要的事件,但是并不是错误时,如用户登录密码错误
  • INFO:处理请求或者状态变化等日常事务
  • DEBUG:调试过程中使用DEBUG等级,如算法中每个循环的中间状态

traceback模块

traceback是python中用来跟踪异常信息的模块,方便把程序中的运行异常打印或者保存下来做异常分析。

常见用法

try:
  doSomething()
except:
  traceback.print_exc()
  # logging.error(str(traceback.format_exc()))

traceback.format_exc() 与 traceback.print_exc() 区别:

  1.    traceback.format_exc() 返回异常信息的字符串,可以用来把信息记录到log里;
  2.    traceback.print_exc() 直接把异常信息在终端打印出来;

traceback.print_exc()也可以实现把异常信息写入文件,使用方法:

traceback.print_exc(file=open('traceback_INFO.txt','w+'))

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

Python Opencv实现图像轮廓识别功能

Python Opencv实现图像轮廓识别功能

本文实例为大家分享了python opencv识别图像轮廓的具体代码,供大家参考,具体内容如下 要求:用矩形或者圆形框住图片中的云朵(不要求全部框出) 轮廓检测 Opencv-Pyth...

python被修饰的函数消失问题解决(基于wraps函数)

这篇文章主要介绍了python被修饰的函数消失问题解决(基于wraps函数),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 当使用@修...

pyqt5 使用cv2 显示图片,摄像头的实例

如下所示: #! /usr/bin/python3 # coding = utf-8 # from PyQt5 import QtGui,QtCore,Qt import sys f...

3行Python代码实现图像照片抠图和换底色的方法

3行Python代码实现图像照片抠图和换底色的方法

1、项目背景 对于不会PS的小伙伴,抠图是一个难度系数想当高的活儿,某宝照片抠图和证件照换底色均价都是5元RMB,所以今天要介绍的这款神工具,只要 3 行代码 5 秒钟就可以完成高精度抠...

Django使用详解:ORM 的反向查找(related_name)

先定义两个模型,一个是A,一个是B,是一对多的类型。 class A(models.Model): name= models.CharField('名称', max_length...