如何只把特定的事情记录到日志文件中?

2024-06-25 22:56:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我在网上刮工作,我应该刮多个网址。我用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
.
.
.

如何确保只在日志文件中启动记录器,而不获取其余的记录器。为什么我在日志文件中得到了额外的内容,尽管我没有明确提到它可以在任何地方记录这些项目。你知道吗

我看起来是不是完全错了?请帮帮我。你知道吗

我试着按照一个答案中的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

Tags: 文件httpsdebugcomnewtimeloggingwww
2条回答

basicConfig中指定日志记录级别:

logging.basicConfig(level=logging.INFO, filename='BOM.log', format=...
logging.info('Logger initiated')

这将忽略比INFO严重的日志消息。你知道吗

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

相关问题 更多 >