【问题标题】:handle all exception in scrapy with sentry用哨兵处理scrapy中的所有异常
【发布时间】:2014-10-05 10:21:49
【问题描述】:

我正在用scrapy做一个项目有一段时间了,我想集成哨兵,

我用过scrapy-sentry,但它根本不起作用

我也尝试使用 Extensions 来实现它,但它只有在蜘蛛的回调(不是 pipelines.py、items.py)中发生错误时才有效......

from scrapy import signals

from raven import Client


class FailLogger(object):
    client = Client(settings.get('SENTRY_DSN'))

    @classmethod
    def from_crawler(cls, crawler):
        ext = cls()

        crawler.signals.connect(ext.spider_error, signal=signals.spider_error)
        return ext

    def spider_error(self, failure, response, spider):
        try:
            failure.raiseException()
        except:
            self.client.get_ident(self.client.captureException())

有没有我可以将错误(在蜘蛛、项目、管道......)记录到哨兵,就像在 Django 中一样?

谢谢。

【问题讨论】:

  • Scrapy users Twisted log 所以我尝试添加一个新的观察者,它是一个在发生错误时调用的回调函数,我刚刚测试了 id,它的工作就像一个魅力!答案:Here

标签: python exception scrapy sentry


【解决方案1】:

这是一篇旧帖子,但我的回答可能对其他人有用。 Raven 被 sentry-python 取代(在 pip 中命名为sentry-sdk)。使用这个新包,有一个比 scrapy-sentry 更简单和完整的解决方案。这是基于scrapy日志功能基于stdlib日志模块的事实。

你可以使用下面这个非常简单的scrapy扩展来捕捉蜘蛛内外的异常和错误(包括下载器中间件、项目中间件等)。

  1. SentryLogging 扩展名添加到您的scrapy 项目的extensions.py 文件中:
import sentry_sdk
from scrapy.exceptions import NotConfigured

class SentryLogging(object):
    """
    Send exceptions and errors to Sentry.
    """

    @classmethod
    def from_crawler(cls, crawler):
        sentry_dsn = crawler.settings.get('SENTRY_DSN', None)
        if sentry_dsn is None:
            raise NotConfigured
        # instantiate the extension object
        ext = cls()
        # instantiate
        sentry_sdk.init(sentry_dsn)
        # return the extension object
        return ext
  1. 将以下行添加到您的settings.py 中,以用低值激活它,以便尽快捕获异常和错误:
# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
EXTENSIONS = {
    'myproject.extensions.SentryLogging': -1, # Load SentryLogging extension before others
}

# Send exceptions to Sentry
# replace SENTRY_DSN by you own DSN
SENTRY_DSN = "XXXXXXXXXX"

确保将SENTRY_DSN替换为相关项目的Sentry DSN。

spider 内部和外部的错误和异常现在应该发送到 Sentry。如果您想进一步自定义发送到 Sentry 的内容,您可能需要根据its documentation 编辑对sentry_sdk.init() 的调用。

【讨论】:

  • 是的,它也是。
  • 这创造了奇迹。应该在官方的 Scrapy 文档中! :)
  • 谢谢 :) 这是个好主意。我可能会尝试看看它在 Scrapy 文档或 Sentry 文档中的位置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
  • 2019-07-11
  • 2016-10-22
  • 1970-01-01
  • 2019-05-31
相关资源
最近更新 更多