python中logging库的使用总结
作者:郭西西 时间:2022-10-29 09:36:28
前言
最近因为工作的需要,在写一些python脚本,总是使用print来打印信息感觉很low,所以抽空研究了一下python的logging库,来优雅的来打印和记录日志,下面话不多说了,来一起看看详细的介绍吧。
一、简单的将日志打印到屏幕:
import logging
logging.debug('This is debug message') #debug
logging.info('This is info message') #info
logging.warning('This is warning message') #warn
屏幕上打印:WARNING:root:This is warning message
默认情况下,会打印WARNING级别的日志
DEBUG:详细信息,调试信息。
INFO:确认一切按预期运行。
WARNING:表明发生了一些意外,或者不久的将来会发生问题(如‘磁盘满了')。软件还是在正常工作。
ERROR:由于更严重的问题,软件已不能执行一些功能了。
CRITICAL:严重错误,表明软件已不能继续运行了。
二、通过basicConfig函数来对日志的输入格式和方法进行配置
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%Y-%m-%d %a %H:%M:%S',
filename='test.log',
filemode='w')
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
以上代码不会在屏幕上打印日志,而是会在当前目录生成test.log的日志文件,日志被打印在日志文件中:
2017-10-16 Mon 10:05:17 testlogging.py[line:25] DEBUG This is debug message
2017-10-16 Mon 10:05:17 testlogging.py[line:26] INFO This is info message
2017-10-16 Mon 10:05:17 testlogging.py[line:27] WARNING This is warning message
logging.basicConfig函数各参数:
filename: 指定日志文件名
filemode: 和file函数意义相同,指定日志文件的打开模式,'w'或'a'
format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:
%(levelno)s: 打印日志级别的数值
%(levelname)s: 打印日志级别名称
%(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
%(filename)s: 打印当前执行程序名
%(funcName)s: 打印日志的当前函数
%(lineno)d: 打印日志的当前行号
%(asctime)s: 打印日志的时间
%(thread)d: 打印线程ID
%(threadName)s: 打印线程名称
%(process)d: 打印进程ID
%(message)s: 打印日志信息
datefmt: 指定时间格式,同time.strftime()
level: 设置日志级别,默认为logging.WARNING
stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略
三、同时将日志输出到屏幕和日志文件
#定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
插入以上代码就可以同时在屏幕上打印出日志
屏幕上打印:
root : INFO This is info message
root : WARNING This is warning message
文件中打印:
2017-10-16 Mon 10:20:07 testlogging.py[line:46] DEBUG This is debug message
2017-10-16 Mon 10:20:07 testlogging.py[line:47] INFO This is info message
2017-10-16 Mon 10:20:07 testlogging.py[line:48] WARNING This is warning message
四、通过配置文件配置日志
#logger.conf
[loggers]
#定义logger模块,root是父类,必需存在的,其它的是自定义。
keys=root,infoLogger,warnlogger
[logger_root]
level=DEBUG #level 级别,级别有DEBUG、INFO、WARNING、ERROR、CRITICAL
handlers=infohandler,warnhandler #handlers 处理类,可以有多个,用逗号分开
[logger_infoLogger] #[logger_xxxx] logger_模块名称
handlers=infohandler
qualname=infoLogger #qualname logger名称,应用程序通过 logging.getLogger获取。对于不能获取的名称,则记录到root模块。
propagate=0 #propagate 是否继承父类的log信息,0:否 1:是
[logger_warnlogger]
handlers=warnhandler
qualname=warnlogger
propagate=0
###############################################
#定义handler
[handlers]
keys=infohandler,warnhandler
[handler_infohandler]
class=StreamHandler #class handler类名
level=INFO #level 日志级别
formatter=form02 #formatter,下面定义的formatter
args=(sys.stdout,) #args handler初始化函数参数
[handler_warnhandler]
class=FileHandler
level=WARN
formatter=form01
args=('logs/deploylog.log', 'a')
###############################################
# 定义格式化输出
[formatters]
keys=form01,form02
[formatter_form01]
format=%(message)s %(asctime)s
datefmt=%Y-%m-%d %H:%M:%S
[formatter_form02]
format=%(asctime)s %(levelname)s %(message)s
datefmt=%Y-%m-%d %H:%M:%S
日志格式
%(asctime)s 年-月-日 时-分-秒,毫秒 2013-04-26 20:10:43,745
%(filename)s 文件名,不含目录
%(pathname)s 目录名,完整路径
%(funcName)s 函数名
%(levelname)s 级别名
%(lineno)d 行号
%(module)s 模块名
%(message)s 消息体
%(name)s 日志模块名
%(process)d 进程id
%(processName)s 进程名
%(thread)d 线程id
%(threadName)s 线程名
测试配置文件
from logging.config import fileConfig
fileConfig('logger.conf')
logger=logging.getLogger('infoLogger')
logger.info('test1')
logger_error=logging.getLogger('warnhandler')
logger_error.warn('test5')
来源:https://segmentfault.com/a/1190000011570197
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
pycharm from lxml import etree标红问题及解决
![](https://img.aspxhome.com/file/2023/0/95780_0s.png)
python+pytest自动化测试函数测试类测试方法的封装
![](https://img.aspxhome.com/file/2023/7/105257_0s.png)
在Typescript中如何使用for...in详解
Golang使用第三方包viper读取yaml配置信息操作
![](https://img.aspxhome.com/file/2023/1/127391_0s.jpg)
MSSQL 事务说明
python利用proxybroker构建爬虫免费IP代理池的实现
![](https://img.aspxhome.com/file/2023/9/130629_0s.jpg)
JavaScript 与 ActionScript 3.0 交互的一些问题
Elasticsearches通过坐标位置实现对附近人的搜索
python分布式计算dispy的使用详解
都2019年了,还问http中GET和POST的区别
![](https://img.aspxhome.com/file/2023/9/132289_0s.jpg)
MySQL中Decimal类型和Float Double的区别(详解)
redis查看连接数及php模拟并发创建redis连接的方法
OpenCV图像变换之傅里叶变换的一些应用
![](https://img.aspxhome.com/file/2023/9/85359_0s.jpg)
MySql 5.6.14 Win32位免安装解压缩版配置教程
mysql语句如何插入含单引号或反斜杠的值详解
python实现解数独程序代码
![](https://img.aspxhome.com/file/2023/8/101318_0s.png)
python 实现倒计时功能(gui界面)
![](https://img.aspxhome.com/file/2023/5/68915_0s.gif)
python密码学简单替代密码解密及测试教程
![](https://img.aspxhome.com/file/2023/2/62852_0s.jpg)
python轻松过滤处理脏话与特殊敏感词汇
如何利用JavaScript读取excel文件并绘制echarts图形
![](https://img.aspxhome.com/file/2023/0/56210_0s.png)