我试图确保日志文件不会超过1048576字节。由于Scrapy使用python logging
模块,我试图将Scrapy的默认FileHandler
更改为RotatingFileHandler
。
我无法在Scrapy文档或设置中找到任何相关信息。我的想法是覆盖蜘蛛的__init__()
方法(我有一只蜘蛛)。
def __init__(self, *a, **kw):
self.logger.logger.root.handlers[-1] = RotatingFileHandler('log.log',maxBytes=1024,backupCount=1)
super(MainSpider, self).__init__(*a, **kw)
但scrapy在蜘蛛初始化之前记录数据。
2017-10-26 13:16:15 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: engine_bot)
2017-10-26 13:16:15 [scrapy.utils.log] INFO: Overridden settings:
....
有没有办法让这个工作或设置Scrapy默认日志文件的最大大小?
答案 0 :(得分:3)
您必须按照configure_logging
中的说明使用install_root_handler=False
致电https://doc.scrapy.org/en/latest/topics/logging.html#module-scrapy.utils.log。
import logging
from logging.handlers import RotatingFileHandler
from scrapy.utils.log import configure_logging
# Disable default Scrapy log settings.
configure_logging(install_root_handler=False)
# Define your logging settings.
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
log_level = logging.INFO # Or better yet get `LOG_LEVEL` from settings.
log_file = 'log.log' # Or better yet get `LOG_FILE` from settings.
logging.basicConfig(
format=log_format,
level=log_level
)
rotating_file_log = RotatingFileHandler(log_file, maxBytes=1024, backupCount=1)
rotating_file_log.setFormatter(logging.Formatter(log_format))
root_logger = logging.getLogger()
root_logger.addHandler(rotating_file_log)
通过这种方式,您将登录到控制台(根据basicConfig
默认设置;但是,可以删除此处理程序)和旋转文件。