手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

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

[日期:2019-05-13] 来源:Linux社区  作者:dcrmg [字体: ]

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"致命错误")

输出如下:

2019-05-13 00:42:13,584 - root -www.linuxidc.com.py[line:7] - DEBUG - 调试
2019-05-13 00:42:13,589 - root -www.linuxidc.com.py[line:8] - INFO - 执行打印功能
2019-05-13 00:42:13,590 - root -www.linuxidc.com.py[line:9] - WARNING - 警告
2019-05-13 00:42:13,590 - root -www.linuxidc.com.py[line:10] - ERROR - 错误
2019-05-13 00:42:13,590 - root -www.linuxidc.com.py[line:11] - CRITICAL - 致命错误

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

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')

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

日志等级划分

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() 区别:

  traceback.format_exc() 返回异常信息的字符串,可以用来把信息记录到log里;
  traceback.print_exc() 直接把异常信息在终端打印出来;
traceback.print_exc() 也可以实现把异常信息写入文件,使用方法:

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

Python skimage模块的安装

pip install scikit-image

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

本文永久更新链接地址https://www.linuxidc.com/Linux/2019-05/158636.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款