Skip to main content
 首页 » 编程设计

python之CrawlerProcess 中的多个蜘蛛之如何获取每个蜘蛛的日志

2024年10月24日10落叶无声

场景:

  • 具有多个蜘蛛的单个 scrapy 项目。
  • 所有蜘蛛从脚本一起运行。

问题:

  • 同一 namespace 中的所有日志消息。不可能知道哪个消息属于哪个蜘蛛。

在 scrapy 0.24 中,我在一个脚本中运行了多个蜘蛛,我得到了一个日志文件,其中包含与其蜘蛛相关的消息,类似于此:

2015-09-30 22:55:12-0400 [scrapy] INFO: Scrapy 0.24.5 started (bot: mybot) 
2015-09-30 22:55:12-0400 [scrapy] DEBUG: Enabled extensions: LogStats, ... 
2015-09-30 21:55:12-0500 [scrapy] DEBUG: Enabled downloader middlewares: HttpAuthMiddleware, ... 
2015-09-30 21:55:12-0500 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMiddleware, ... 
2015-09-30 21:55:12-0500 [scrapy] DEBUG: Enabled item pipelines: MybotPipeline 
2015-09-30 21:55:12-0500 [spider1] INFO: Spider opened 
2015-09-30 21:55:12-0500 [spider1] INFO: Crawled 0 pages ... 
2015-09-30 21:55:12-0500 [spider2] INFO: Spider opened 
2015-09-30 21:55:12-0500 [spider2] INFO: Crawled 0 pages ... 
2015-09-30 21:55:12-0500 [spider3] INFO: Spider opened 
2015-09-30 21:55:12-0500 [spider3] INFO: Crawled 0 pages ... 
2015-09-30 21:55:13-0500 [spider2] DEBUG: Crawled (200) <GET ... 
2015-09-30 21:55:13-0500 [spider3] DEBUG: Crawled (200) <GET ... 
2015-09-30 21:55:13-0500 [spider1] DEBUG: Crawled (200) <GET ... 
2015-09-30 21:55:13-0500 [spider1] INFO: Closing spider (finished) 
2015-09-30 21:55:13-0500 [spider1] INFO: Dumping Scrapy stats: ... 
2015-09-30 21:55:13-0500 [spider3 INFO: Closing spider (finished) 
2015-09-30 21:55:13-0500 [spider3] INFO: Dumping Scrapy stats: ... 
2015-09-30 21:55:13-0500 [spider2] INFO: Closing spider (finished) 
2015-09-30 21:55:13-0500 [spider2] INFO: Dumping Scrapy stats: ... 

有了这个日志文件,我可以在需要时运行 grep spiderX logfile.txt 来获取与某个特定蜘蛛相关的日志。但是现在,在 scrapy 1.0 中,我得到:

2015-09-30 21:55:12-0500 [scrapy] INFO: Spider opened 
2015-09-30 21:55:12-0500 [scrapy] INFO: Crawled 0 pages ... 
2015-09-30 21:55:12-0500 [scrapy] INFO: Spider opened 
2015-09-30 21:55:12-0500 [scrapy] INFO: Crawled 0 pages ... 
2015-09-30 21:55:12-0500 [scrapy] INFO: Spider opened 
2015-09-30 21:55:12-0500 [scrapy] INFO: Crawled 0 pages ...  

显然不可能知道哪个消息属于每个蜘蛛。

问题是:有没有办法让之前的行为有?

每个蜘蛛都有不同的日志文件也是可能的。 [1]
但是不可能使用 custom_settings 覆盖爬虫中的日志文件。 [2]

那么,有什么办法可以让每个蜘蛛都有不同的日志文件吗?

[1] Scrapy Project with Multiple Spiders - Custom Settings Ignored
[2] https://github.com/scrapy/scrapy/issues/1612

请您参考如下方法:

我刚刚发现这是一个已知的“错误”:https://github.com/scrapy/scrapy/issues/1576

已知解决方案:将 utils.log.TopLevelFormatter.filter 更改为

def filter(self, record): 
    if hasattr(record, 'spider'):  
        record.name = record.spider.name 
    elif any(record.name.startswith(l + '.') for l in self.loggers): 
        record.name = record.name.split('.', 1)[0] 
    return True