Scrapy:不使用ScrapyFileLogObserver()登录到文件

2024-04-24 11:15:04 发布

您现在位置:Python中文网/ 问答频道 /正文

显然,我不应该再使用ScrapyFileLogObserver(http://doc.scrapy.org/en/1.0/topics/logging.html)。但是我仍然希望能够将日志消息保存到一个文件中,并且我仍然希望所有标准的Scrapy控制台信息也保存到该文件中。在

通过阅读如何使用日志模块,以下是我尝试使用的代码:

class BlahSpider(CrawlSpider):
    name = 'blah'
    allowed_domains = ['blah.com']
    start_urls = ['https://www.blah.com/blahblahblah']

    rules = (
        Rule(SgmlLinkExtractor(allow=r'whatever'), callback='parse_item', follow=True),
    )

    def __init__(self):
        CrawlSpider.__init__(self)
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.DEBUG)
        logging.basicConfig(filename='debug_log.txt', filemode='w', format='%(asctime)s %(levelname)s: %(message)s',
                            level=logging.DEBUG)
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        simple_format = logging.Formatter('%(levelname)s: %(message)s')
        console.setFormatter(simple_format)
        self.logger.addHandler(console)
        self.logger.info("Something")

    def parse_item(self):
        i = BlahItem()
        return i

它运行良好,并将“某物”保存到文件中。但是,我在命令提示符窗口中看到的所有内容,以及在我使用ScrapyFileLogObserver时保存到文件中的所有内容现在都没有保存。在

我以为我的“控制台”处理程序日志记录.StreamHandler()“本来应该处理这个问题的,但这只是我读过的,我真的不明白它是怎么工作的。在

有人能指出我遗漏了什么或哪里出了问题吗?在

谢谢。在


Tags: 文件debugselfcomformatparseinitlogging
2条回答

您可以先在中禁用根句柄,将所有零碎日志记录到文件中scrapy.utils.log。配置日志记录,然后添加自己的日志处理程序。在

在设置.pyscrapy project文件添加以下代码:

import logging
from logging.handlers import RotatingFileHandler

from scrapy.utils.log import configure_logging

LOG_ENABLED = False
# Disable default Scrapy log settings.
configure_logging(install_root_handler=False)

# Define your logging settings.
log_file = '/tmp/logs/CRAWLER_logs.log'

root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
rotating_file_log = RotatingFileHandler(log_file, maxBytes=10485760, backupCount=1)
rotating_file_log.setLevel(logging.DEBUG)
rotating_file_log.setFormatter(formatter)
root_logger.addHandler(rotating_file_log)

我们还根据需要定制日志级别(调试到信息)和格式化程序。 希望这有帮助!在

我认为问题是您同时使用了basicConfig和{}。在

分别配置两个处理程序:

self.logger = logging.getLogger()
self.logger.setLevel(logging.DEBUG)

logFormatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')

# file handler
fileHandler = logging.FileHandler("debug_log.txt")
fileHandler.setLevel(logging.DEBUG)
fileHandler.setFormatter(logFormatter)
self.logger.addHandler(fileHandler)

# console handler
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.DEBUG)
consoleHandler.setFormatter(logFormatter)
self.logger.addHandler(consoleHandler)

另请参见:

相关问题 更多 >