我正在编写网络抓取工具并遇到问题,我想将每个不同级别的消息记录到自己的日志文件中。
我认为这样可行,但它只会创建' crawler-debug.log'
logging.basicConfig(level=logging.DEBUG, filename='crawler-debug.log')
logging.basicConfig(level=logging.WARN, filename='crawler-warn.log')
logging.basicConfig(level=logging.ERROR, filename='crawler-error.log')
logging.basicConfig(level=logging.INFO, filename='crawler-info.log')
我在哪里错了...
此外,我想在日志文件的每一行的开头添加时间戳,以便我知道请求何时发送。
答案 0 :(得分:0)
您需要为每个日志级别创建一个文件处理程序。可以将格式应用于每个处理程序以添加时间戳。 Python Logging Cookbook - Multiple handlers and formatters
另外,要过滤掉所需的其他日志级别(例如,只有DEBUG日志记录转到调试日志文件),您需要编写自己的处理程序对象。 See similar question answered here.
这是一个只有调试和信息记录的例子。
import logging
# Define handler to omit logs that are not DEBUG level
class DebugFileHandler(logging.FileHandler):
def __init__(self, filename, mode='a', encoding=None, delay=False):
logging.FileHandler.__init__(self, filename, mode, encoding, delay)
def emit(self, record):
if not record.levelno == logging.DEBUG:
return
logging.FileHandler.emit(self, record)
# Define handler to omit logs that are not INFO level
class InfoFileHandler(logging.FileHandler):
def __init__(self, filename, mode='a', encoding=None, delay=False):
logging.FileHandler.__init__(self, filename, mode, encoding, delay)
def emit(self, record):
if not record.levelno == logging.INFO:
return
logging.FileHandler.emit(self, record)
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create file handlers
dh = DebugFileHandler('debug.log')
dh.setLevel(logging.DEBUG)
ih = InfoFileHandler('info.log')
ih.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(message)s')
dh.setFormatter(formatter)
ih.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ih)
logger.addHandler(dh)
# 'application' code
logger.debug('debug message')
logger.info('info message')