scrapy 中日志的使用

我在后台调试 在后台调试scrapy spider的时候,总是觉得后台命令窗口 打印的东西太多了不便于观察日志,因此需要一个日志文件记录信息,这样以后会 方便查找问题。

 

分两种方法吧。

 

1.简单粗暴。直接命令里面配置LOG_FILE

scrapy crawl hupu -s LOG_FILE=scrapy_hupu_log.log

2.使用logging

在setting中加入配置
LOG_FILE = "hupuSpider.log"
LOG_LEVEL = 'INFO'
# LOG_ENABLED 默认: True,启用logging
# LOG_ENCODING 默认: 'utf-8',logging使用的编码
# LOG_FILE 默认: None,在当前目录里创建logging输出文件的文件名
# LOG_LEVEL 默认: 'DEBUG',log的最低级别
# LOG_STDOUT 默认: False 如果为 True,进程所有的标准输出(及错误)将会被重定向到log中。例如,执行 print "hello" ,其将会在Scrapy log中显示

使用 

import logging

logging.log(logging.INFO, 'log content')

logging模块是Python提供的自己的程序日志记录模块。

在大型软件使用过程中,出现的错误有时候很难进行重现,因此需要通过分析日志来确认错误位置,这也是写程序时要使用日志的最重要的原因。

scrapy使用python内置的logging模块记录日志


日志的级别

1. logging.CRITICAL - for critical errors (highest severity)

2. logging.ERROR - for regular errors

3. logging.WARNING - for warning messages

4. logging.INFO - for informational messages

5. logging.DEBUG - for debugging messages (lowest severity)


基本使用方法

1.简单使用方法

import logging

Logging.warning(“this is a test ”)

执行结果:

Python1.png 

2.通用的记录日志的方法,可加入日志的级别

import logging

Logging.log(logging.WARNING,”this is a warning”)

3,通过logger记录日志

import logging

logger=logging.getLogger(_name_)

Logger.warning(“this is a warning”)


在scrapy中使用

Scrapy provides a logger within each Spider instance, that can be accessed and used like this:

import scrapy

class MySpider(scrapy.Spider):

name = 'myspider'

start_urls = ['http://scrapinghub.com']

def parse(self, response):

self.logger.info('Parse function called on %s', response.url)

That logger is created using the Spider’s name, but you can use any custom Python logger you want. For example:

import logging import scrapy

logger = logging.getLogger('mycustomlogger')

class MySpider(scrapy.Spider):

name = 'myspider'

start_urls = ['http://scrapinghub.com']

def parse(self, response):

logger.info('Parse function called on %s', response.url)


 

在settings.py中配置

These settings can be used to configure the logging:

 

• LOG_FILE 

• LOG_ENABLED

• LOG_ENCODING

• LOG_LEVEL 

• LOG_FORMAT 

• LOG_DATEFORMAT 

• LOG_STDOUT

 可参考https://www.cnblogs.com/sufei-duoduo/p/5880988.html,https://doc.scrapy.org/en/0.12/topics/logging.html,https://www.cnblogs.com/similarface/p/5179193.html

posted @ 2018-02-08 11:50  fredgui  阅读(2150)  评论(0编辑  收藏  举报