繁体   English   中英

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

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

我正在使用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)
  ......

现在,如果我开始Spider_One ,一切都是正确的!但是,如果我开始Spider Two ,的日志文件Spider Two还将与名称命名的Spider One
我已经从Google和stackoverflow搜索了很多答案,但不幸的是,没有一个有效!
我正在使用python 2.7和scrapy 1.1!
希望任何人都能帮助我!

这是因为每次加载程序包时都会启动logging_to_file 您在此处使用类变量,应在其中使用实例变量。

当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

要解决您的问题,只需将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