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')
日志等级划分
traceback模块
traceback是python中用来跟踪异常信息的模块,方便把程序中的运行异常打印或者保存下来做异常分析。
常见用法
try: doSomething()except: traceback.print_exc() # logging.error(str(traceback.format_exc()))
traceback.format_exc() 与 traceback.print_exc() 区别:
traceback.print_exc()
也可以实现把异常信息写入文件,使用方法:
traceback.print_exc(file=open('traceback_INFO.txt','w+'))
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对武林网的支持。如果你想了解更多相关内容请查看下面相关链接
新闻热点
疑难解答
图片精选