1.爬取时如何显示日志的问题
logging.captureWarnings(True)
引入模块 import logging
# 日志级别
# CRITICAL 50
# ERROR 40
# WARNING 30
# INFO 20
# DEBUG 10
只有在30以上级别的才显示
logging.Error('debug message')
logging.CRITICAL('info message')
将文本写入日志
import os
logging.basicConfig(filename=os.path.join(os.getcwd(),'log.txt'),level=logging.DEBUG)
logging.debug('this is a message')
自定义输出格式
# -*-coding:utf-8-*-
import logging
def console_out(logFilename):
''''' Output log to file and console '''
# Define a Handler and set a format which output to file
logging.basicConfig(
level=logging.DEBUG, # 定义输出到文件的log级别,大于此级别的都被输出
format='%(asctime)s %(filename)s : %(levelname)s %(message)s', # 定义输出log的格式
datefmt='%Y-%m-%d %A %H:%M:%S', # 时间
filename=logFilename, # log文件名
filemode='w') # 写入模式“w”或“a”
# Define a Handler and set a format which output to console
console = logging.StreamHandler() # 定义console handler
console.setLevel(logging.INFO) # 定义该handler级别
formatter = logging.Formatter('%(asctime)s %(filename)s : %(levelname)s %(message)s') # 定义该handler格式
console.setFormatter(formatter)
# Create an instance
logging.getLogger().addHandler(console) # 实例化添加handler
# Print information # 输出日志级别
logging.debug('logger debug message')
logging.info('logger info message')
logging.warning('logger warning message')
logging.error('logger error message')
logging.critical('logger critical message')
if __name__ == "__main__":
console_out('logging.log')
自定义输出位置
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='/tmp/test.log',
filemode='w')
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')