如何仅将特定内容记录到日志文件中?

3
我正在进行Web抓取,需要抓取多个URL。我正在使用ThreadPoolExecutor来完成任务。 我还想在其中实现日志记录。我只想将特定的调试、信息或警告语句写入日志文件中。但实际上它会将每个请求都写入日志文件。 如何让它只写入我用logging.infologging.warning等指定的特定语句到文件中。 以下是我的代码片段:
logging.basicConfig(filename='BOM.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('Logger initiated')

with ThreadPoolExecutor(max_workers=100) as executor:
    startt = time.time()
    futures = [executor.submit(get_movie_details, movie_id) for movie_id in all_movies_ids]
    for result in as_completed(futures):
        all_movies_summary_data.append(result)
    endt = time.time()
    print("Time Taken: {:.6f}s".format(endt - startt))

以下是日志文件的样子:

2019-03-31 16:21:04,722 - DEBUG - Logger initiated
2019-03-31 16:21:04,731 - DEBUG - Starting new HTTPS connection (1): www.boxofficemojo.com:443
2019-03-31 16:21:04,733 - DEBUG - Starting new HTTPS connection (2): www.boxofficemojo.com:443
2019-03-31 16:21:04,736 - DEBUG - Starting new HTTPS connection (3): www.boxofficemojo.com:443
.
.
.

我该如何确保只获取记录在日志文件中的Logger,而不是其他内容。尽管我没有明确地说明要记录那些项,为什么日志文件中会出现额外的内容。

我是否完全错误地理解了日志记录或其他事情?

我尝试按照glhr在其中一个答案中建议的设置日志级别。

但它的输出结果如下所示。

2019-03-31 17:07:29,817 - INFO - Logger initiated
2019-03-31 17:07:30,981 - WARNING - Connection pool is full, discarding connection: www.boxofficemojo.com
2019-03-31 17:07:30,994 - WARNING - Connection pool is full, discarding connection: www.boxofficemojo.com
2019-03-31 17:07:30,997 - WARNING - Connection pool is full, discarding connection: www.boxofficemojo.com

2
如果您真正寻求适用于Python 2和Python 3的可移植解决方案,请[编辑]您的问题以详细说明此要求。如果不是,请删除至少一个误导性标签。 - tripleee
这是一个可行的解决方案链接 - kappa101
2个回答

3

logging.basicConfig 配置了日志记录器,其他日志记录器都继承自它。

因此,使用此方法设置的日志配置将应用于其他模块记录的日志,因此在日志文件中会出现额外的日志行。

为了仅记录您自己的消息:

(摘自https://docs.python.org/3/howto/logging.html#logging-advanced-tutorial)

import logging

# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# create file handler and set level to INFO
file_handler = logging.FileHandler('BOM.log')
file_handler.setLevel(logging.INFO)
logger.addHandler(file_handler)

# 'application code'
logger.debug('not shown in log file')
logger.info('info message in log file')
logger.warning('warning message in log file')
logger.error('error message in log file')

结果 BOM.log

info message in log file
warning message in log file
error message in log file

1

basicConfig中指定日志记录级别:

logging.basicConfig(level=logging.INFO, filename='BOM.log', format=...
logging.info('Logger initiated')
这将忽略比INFO更不严重的日志信息。

1
消息也可以通过它们的来源和内容进行过滤,因为您使用的模块也会产生自己的日志输出。 - Dan D.
请查看问题中的更新内容。我尝试了你说的方法,但是输出结果不同。它们仍然以“警告”级别打印。 - Underoos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,