首页 > 编程 > Python > 正文

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

2019-11-25 13:02:46
字体:
来源:转载
供稿:网友

logging模块

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

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

#!/usr/bin/env python# -*- coding:utf-8 -*-import logging # 引入logging模块# 设置打印日志级别 CRITICAL > ERROR > WARNING > INFO > DEBUGlogging.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# 第一步,创建一个loggerlogger = logging.getLogger()logger.setLevel(logging.DEBUG) # Log等级开关# 第二步,创建一个handler,用于写入日志文件log_path = os.path.dirname(os.getcwd()) + '/Logs/'log_name = log_path + 'log.log'logfile = log_namefile_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)# 如果需要同需要在端上出,定一streamHandlerprint_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')# 或使用logginglogging.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+'))

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对武林网的支持。如果你想了解更多相关内容请查看下面相关链接

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表