python之logging模块简单用法
前言:
python引入logging模块,用来记录自己想要的信息。print也可以输入日志,但是logging相对print来说更好控制输出在哪个地方。怎么输出以及控制消息级别来过滤掉那些不需要的信息。
日志级别:
代码:
1 # coding:utf-8 2 import logging # 引入logging模块 3 4 # 将信息打印到控制台上 5 6 # 如果需要显示低于WARNING级别的内容,可以引入NOTSET级别来显示 7 logging.basicConfig(level=logging.NOTSET) # 设置日志级别 8 logging.debug(u"小花") 9 logging.info(u"如果设置了日志级别为NOTSET,那么这里可以采取debug、info的级别的内容也可以显示在控制台上了") 10 11 logging.warning(u"小丽") 12 logging.error(u"zxc") 13 logging.critical(u"qwe") 14 # 正常情况下只能看到后面三个能打印出来。因为:默认生成的root logger的level是logging.WARNING,低于该级别的就不输出了。级别排序:CRITICAL > ERROR > WARNING > INFO > DEBUG
执行结果:
DEBUG:root:小花 INFO:root:如果设置了日志级别为NOTSET,那么这里可以采取debug、info的级别的内容也可以显示在控制台上了 WARNING:root:小丽 ERROR:root:zxc CRITICAL:root:qwe
日志输出-控制台:
代码:
1 # coding:utf-8 2 import logging # 引入logging模块 3 4 # 通过logging.basicConfig 函数进行配置了日志级别和日志内容输出格式 5 logging.basicConfig(level=logging.DEBUG, 6 format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') # logging.basicConfig函数对日志的输出格式及方式做相关配置 7 # 因为日志基本配置中级别设置为DEBUG,所以会将DEBUG级别以上的信息都输出显示再控制台上 8 logging.debug('this is a loggging debug message') 9 logging.info('this is a loggging info message') 10 logging.warning('this is loggging a warning message') 11 logging.error('this is an loggging error message') 12 logging.critical('this is a loggging critical message')
执行结果:
2018-07-20 10:17:54,727 - logging1.py[line:8] - INFO: this is a loggging info message 2018-07-20 10:17:54,805 - logging1.py[line:9] - DEBUG: this is a loggging debug message 2018-07-20 10:17:54,805 - logging1.py[line:10] - WARNING: this is loggging a warning message 2018-07-20 10:17:54,805 - logging1.py[line:11] - ERROR: this is an loggging error message 2018-07-20 10:17:54,805 - logging1.py[line:12] - CRITICAL: this is a loggging critical message
日志输出-控制台和文件、捕获异常:
代码:
1 # coding:utf-8 2 import logging # 引入logging模块 3 import time 4 5 # 第一步,创建一个logger 6 logger = logging.getLogger() # 获取logger实例,如果参数为空,则返回root logger,即默认的logger名称是root 7 logger.setLevel(logging.INFO) # Log等级总开关. logger.setLevel()设置日志级别 8 9 # 第二步,创建一个handler,用于写入日志文件 10 rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time())) 11 logfile = rq + ".log" 12 fh = logging.FileHandler(logfile, mode='w') 13 fh.setLevel(logging.DEBUG) # 输出到file的log等级的开关 14 15 # 同时输出到控制台 16 ch = logging.StreamHandler() 17 ch.setLevel(logging.WARNING) 18 19 # 第三步,定义handler的输出格式 20 # 配置日志的格式 21 formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s") 22 fh.setFormatter(formatter) # 设置Formatter 23 ch.setFormatter(formatter) 24 25 # 第四步,将logger添加到handler里面 26 logger.addHandler(fh) # 添加一个Handler 27 logger.addHandler(ch) 28 29 # 使用logger.XX来记录错误,这里的"error"可以根据所需要的级别进行修改 30 try: 31 open('/path/to/does/not/exist', 'rb') 32 except (SystemExit, KeyboardInterrupt): 33 raise 34 except Exception as e: 35 logger.error('Failed to open file', exc_info=False) # 如果要求日志上报错误,可以将exc_info设置为True. 36 37 # # 日志 38 # logger.debug('this is a logger debug message') 39 # logger.info('this is a logger info message') 40 # logger.warning('this is a logger warning message') 41 # logger.error('this is a logger error message') 42 # logger.critical('this is a logger critical message')
执行结果:
2018-07-20 10:45:11,936 - logging1.py[line:35] - ERROR: Failed to open file # 文件和控制台上是一致的
日志的输出顺序和模块的执行顺序是一致的。
注意:
“AttributeError:moudle 'logging' has no attribute 'basicConfig'”——原因为:把文件名命名为logging.py导致该错误。
参考链接:
https://www.cnblogs.com/CJOKER/p/8295272.html
https://blog.csdn.net/zyz511919766/article/details/25136485
转载于:https://www.cnblogs.com/sunshine-blog/p/9340297.html
python之logging模块简单用法相关推荐
- python subprocess_python2 subprocess 模块简单用法
subprocess 主要提供了两种常用的方式: subprocess: call/check_call/check_output 直接调用命令的快捷函数:call(), check_call(), ...
- Python中logging模块的基本用法
本文首发于:行者AI 在开发项目时,我们不可能将所有的信息都打印在控制台中.我们可以使用Python标准库提供的logging API来处理.相比print,logging模块提供了许多强大而灵活的功 ...
- python之 logging模块详细使用【转载】
很多程序都有记录日志的需求,并且日志中包含的信息既有正常的程序访问日志,还可能有错误.警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,主要用于输出 ...
- python中config方法作用,python中ConfigParse模块的用法
本文实例讲述了python中ConfigParse模块的用法,分享给大家供大家参考.具体方法如下: 写配置一般用ConfigParse.RawConfigParse类 读配置用ConfigParse. ...
- python中heapq的库是什么_详解Python中heapq模块的用法
详解Python中heapq模块的用法 来源:中文源码网 浏览: 次 日期:2018年9月2日 [下载文档: 详解Python中heapq模块的用法.txt ] (友情提示:右键点上行t ...
- Python 日志logging模块初探及多线程踩坑(2)
系列文章: Python 日志logging模块初探及多线程踩坑(1) Python 日志logging模块初探及多线程踩坑(2) 接着上面一篇文章,我们这篇来写一个多进程兼容且无损性能的 Timed ...
- 【Python】pathlib 模块的用法(Path)
[Python]pathlib 模块的用法 文章目录 [Python]pathlib 模块的用法 1. 介绍 2. 举例 2.1 获取目录 2.2 目录拼接 2.3 创建.删除目录 2.4 读写文件 ...
- python 彩票排列组合_对福彩3D号码进行排列组合为例学习Python的itertools模块的用法...
这里我们以对福彩3D号码进行排列组合为例学习Python的itertools模块的用法.首先我们选择心仪的号码.比如我们选择4,5,7,8 第一种我们只要组六的组合.代码如下 import itert ...
- python 之logging 模块
很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误.警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,loggin ...
- python stdout_详解使用python的logging模块在stdout输出的两种方法
详解使用python的logging模块在stdout输出 前言: 使用python的logging模块时,除了想将日志记录在文件中外,还希望在前台执行python脚本时,可以将日志直接输出到标准输出 ...
最新文章
- FutureTask demo
- Java类与匿名内部类
- FragmentPagerAdapter与FragmentStatePagerAdapter使用详解与区别
- 微信小程序开发第二弹
- mysql最常用的索引_mysql常用索引
- java 根据类路径获取类_Java类加载器
- ArcSDE的版本管理机制
- 一封遗失信件成就的科技亿万富翁
- Matlab提取ABAQUS后处理文件inp中的节点数
- Ubuntu搜狗输入法乱码
- 雅虎再掀高管离职潮 博客列三大原因
- 浅析iOS程序设计模式(基于MVC)
- Esp8266+ssd1306液晶屏+microPython
- 苹果手机怎么扩大内存_一招教你扩大手机虚拟内存,免费换个新手机
- 第十一届“蓝狐网络杯”湖南省大学生计算机程序设计竞赛
- 聊聊这个本不存在的 “元宇宙”
- 硬盘克隆工具Linux,硬盘克隆(FarStone DriveClone)下载_硬盘克隆(FarStone DriveClone)官方下载-太平洋下载中心...
- 周志明 java_周志明
- 图解希尔排序(Shell Sort)
- Java实现99乘法表