Scrapy:在没有 ScrapyFileLogObserver() 的情况下记录到文件

jkd*_*une 3 python logging scrapy

显然,我不应该再使用 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
Run Code Online (Sandbox Code Playgroud)

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

我认为我的带有“logging.StreamHandler()”的“控制台”处理程序应该处理这个问题,但这只是我读过的,我并不真正理解它是如何工作的。

谁能指出我遗漏了什么或我哪里出错了?

谢谢你。

ale*_*cxe 5

我认为问题在于您同时使用了basicConfigaddHandler

分别配置两个处理程序:

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)
Run Code Online (Sandbox Code Playgroud)

也可以看看: