stats.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334
  1. from scrapy.exceptions import NotConfigured
  2. from scrapy.utils.request import request_httprepr
  3. from scrapy.utils.response import response_httprepr
  4. from scrapy.utils.python import global_object_name
  5. class DownloaderStats(object):
  6. def __init__(self, stats):
  7. self.stats = stats
  8. @classmethod
  9. def from_crawler(cls, crawler):
  10. if not crawler.settings.getbool('DOWNLOADER_STATS'):
  11. raise NotConfigured
  12. return cls(crawler.stats)
  13. def process_request(self, request, spider):
  14. self.stats.inc_value('downloader/request_count', spider=spider)
  15. self.stats.inc_value('downloader/request_method_count/%s' % request.method, spider=spider)
  16. reqlen = len(request_httprepr(request))
  17. self.stats.inc_value('downloader/request_bytes', reqlen, spider=spider)
  18. def process_response(self, request, response, spider):
  19. self.stats.inc_value('downloader/response_count', spider=spider)
  20. self.stats.inc_value('downloader/response_status_count/%s' % response.status, spider=spider)
  21. reslen = len(response_httprepr(response))
  22. self.stats.inc_value('downloader/response_bytes', reslen, spider=spider)
  23. return response
  24. def process_exception(self, request, exception, spider):
  25. ex_class = global_object_name(exception.__class__)
  26. self.stats.inc_value('downloader/exception_count', spider=spider)
  27. self.stats.inc_value('downloader/exception_type_count/%s' % ex_class, spider=spider)