zoukankan      html  css  js  c++  java
  • python爬虫-scrapy日志

    1、scrapy日志介绍

    Scrapy的日志系统是实现了对python内置的日志的封装

     

     scrapy也使用python日志级别分类

    logging.CRITICAL

    logging.ERROE

    logging.WARINING

    logging.INFO

    logging.DEBUG

    2、如何在python中使用日志呢?

    import logging

    (1)日志对应的格式字符串

    (2)创建一个logger

    logger = logging.getLogger("%s_log" %__name__)

    logger.setLevel(logging.INFO)  # 设定日志等级

    (3)创建一个handler,用于写入日志文件

    fh = logging.FileHandler("test.log", mode="a")

    fh.setLevel(logging.WARNING)

    (4)定义handler的输出格式

    formatter = logging.Formatter("%(asctime)s - %(filename)s [line:%(lineno)d] - %(levelname)s: %(message)s")

    fh.setFormatter(formatter)

    (5)将对应的handler添加在logger对象中

    logger.addHandle(fh)

    (6)正常使用logger.log、logger.debug、logger.info、logger.warning、logger.error、logger.critical

    logger.log(level, msg, *args, **kwargs)

    logger.debug(msg, *args, **kwargs)

    (7)还有一种简单地使用日志的方法,没有上面那么繁琐:

    logging.baseConfig()参数信息如下:

    import logging
    
    logging.baseConfig(filename="", filemode="", format="", datefmt="", stylefmt="", style="", level="", stream="")
    
    logging.info(msg, *args, **kw)
    loggin.debug(msg, *args, **kw)
    logging.warning(msg, *args, **kw)

    3、如何在scrapy中配置日志呢?

    在scrapy中使用日志很简单,只需在settings.py中设置LOG_FILE和LOG_LEVEL两个配置项就可以了

    # 一般在使用时只会设置LOG_FILE和LOG_LEVEL两个配置项,其他配置项使用默认值
    
    # 指定日志的输出文件
    LOG_FILE
    # 是否使用日志,默认为True
    LOG_ENABLED
    # 日志使用的编码,默认为UTF-8
    LOG_ENCODING
    # 日志级别,如果设置了,那么高于该级别的就会输入到指定文件中
    LOG_LEVEL
    # 设置日志的输出格式
    LOG_FORMAT
    # 设置日志的日期输出格式
    LOG_DATEFORMAT
    # 设置标准输出是否重定向到日志文件中,默认为False,如果设置为True,那么print("hello")就会被重定向到日志文件中
    LOG_STDOUT
    # 如果设置为True,只会输出根路径,不会输出组件,默认为FALSE
    LOG_SHORT_NAMES

    一般配置:

    import logging
    
    LOG_FILE="scrapy.log"
    
    # LOG_LEVEL=logging.DEBUG|logging.INFO|logging.WARNING|logging.ERROR|logging.CRITICAL
    
    LOG_LEVEL="DEBUG"

    4、如何在scrapy的组件中使用自输出日志呢?

    我们在控制台下跑爬虫时出现的一系列输出都是有scrapy的日志系统在各组件中自行配置的,我们也可以在我们编写的组件中,自己输出一些日志,用于检测

    控制台中输出的日志:

     下面是从Spider类中抽出来的一个属性,在自构造的爬虫类中self.logger返回一个<class 'LoggerAdapter'>对象,而这个对象中有log、debgu、info等方法,所以我们可以在爬虫组件中使用self.logger.log()、self.logger.debug()等来输出日志,而在其它组件中,会将spider作为参数传进其他组件对象的方法中,所以我们也可以在其它组件中使用spider.logger.log()、spider.logger.debug()等在输出日志。

    @property
        def logger(self):
            logger = logging.getLogger(self.name)
            return logging.LoggerAdapter(logger, {'spider': self})
  • 相关阅读:
    python的多线程是否没有用了
    解决“mongoengine.fields.ImproperlyConfigured: PIL library was not found”报错
    Django JSON 时间
    伪装浏览器根据经纬度解析地理位置
    Excel——使用VLOOKUP函数关联跨工作薄数据
    Python发送邮件(支持中文)
    Excel实用技巧
    修改tomcat应用日志默认编码格式
    AWS多个EIP的解决方案
    解决荣耀7烦人的情景智能提醒
  • 原文地址:https://www.cnblogs.com/loveprogramme/p/12028112.html
Copyright © 2011-2022 走看看