简体   繁体   English

如何使用scrapy的蜘蛛网名称指定日志文件名?

[英]How to specify log file name with spider's name in scrapy?

I'm using scrapy,in my scrapy project,I created several spider classes,as the official document said,I used this way to specify log file name: 我正在使用scrapy,在我的scrapy项目中,我创建了几个Spider类,如官方文档所述,我使用这种方式来指定日志文件名:

 def logging_to_file(file_name):
"""
@rtype: logging
@type file_name:str
@param file_name:
@return:
"""
import logging
from scrapy.utils.log import configure_logging
configure_logging(install_root_handler=False)
logging.basicConfig(
    filename=filename+'.txt',
    filemode='a',
    format='%(levelname)s: %(message)s',
    level=logging.DEBUG,

)
 Class Spider_One(scrapy.Spider):
      name='xxx1'
      logging_to_file(name)
  ......
 Class Spider_Two(scrapy.Spider):
      name='xxx2'
      logging_to_file(name)
  ......

Now,if I start Spider_One ,everything is correct!But,if I start Spider Two ,the log file of Spider Two will also be named with the name of Spider One ! 现在,如果我开始Spider_One ,一切都是正确的!但是,如果我开始Spider Two ,的日志文件Spider Two还将与名称命名的Spider One
I have searched many answers from google and stackoverflow,but unfortunately,none worked! 我已经从Google和stackoverflow搜索了很多答案,但不幸的是,没有一个有效!
I am using python 2.7 & scrapy 1.1! 我正在使用python 2.7和scrapy 1.1!
Hope anyone can help me! 希望任何人都能帮助我!

It's because you initiate logging_to_file every time when you load up your package. 这是因为每次加载程序包时都会启动logging_to_file You are using a class variable here where you should use instance variable. 您在此处使用类变量,应在其中使用实例变量。

When python loads in your package or module ir loads every class and so on. 当python载入您的包或模块时,ir会载入每个类,依此类推。

class MyClass:
    # everything you do here is loaded everytime when package is loaded
    name = 'something'

    def __init__(self):
        # everything you do here is loaded ONLY when the object is created
        # using this class

To resolve your issue just move logging_to_file function call to your spiders __init__() method. 要解决您的问题,只需将logging_to_file函数调用移至logging_to_file __init__()方法即可。

class MyClass(Spider):
    name = 'xx1'

    def __init__(self):
        super(MyClass, self).__init__()
        logging_to_file(self.name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM