logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等
Scrapy中日志的设置
scrapy的setting.py中加入log_lever的设置
LOG_LEVEL="WARNING"
#保存日志文件,则不会输出显示
#LOG_FILE="./log.log"
在写的爬虫代码spider中加入以下代码,同理pipeline也可以实例化一个logger,获得日志文件
import logging
import scrapy
#实例化一个logger,获得日志来自哪个文件
logger = logging.getLogger(__name__)
class ItcastSpider(scrapy.Spider):
name = 'itcast'
allow_domains = ['itcast.cn']
start_urls = ["https://www.itcast.cn"]
def parse(self,response):
for i in range(10):
item = {}
item['come_from'] = 'itcast'
logger.warning(item)
yield item
普通文件中日志的设置案例
logging.basicConfig()的参数:
level:输出日志的等级,debug<info<warning<critical<error
format:输出格式
datemat:时间信息
filename:日志信息输出到的日志文件名
filemode:决定使用什么模式来打开日志文件('r'、'w'、'a'),默认为'a'
import logging
'''format=%(asctime)s具体时间 %(filename)s文件名 %(lenvelname)s日志等级 %(message)s具体信息
datemt=%a星期 %d日期 %b月份 %Y年份 %H:%M:%S时间'''
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s %(levelname)s %(message)s',
datefmt='%a %d %b %Y %H:%M:%S', filename='my.log', filemode='w')
logger=logging.getLogger(__name__)
if __name__=='__main__':
logger.warning('this is warning')
logger.info('this is info')
logger.debug('this is debug')
logger.error('this is error')
logger.critical('this is critical')
总结:
- scrapy的setting文件设置好后-->import logging-->实例化logger,在任何文件中使用logger输出内容
- 普通项目中设置日志输出样式,实例化logger后,在任何py文件中调用logger
logging学习参考文章
https://blog.csdn.net/sinat_34166518/article/details/84028155