Skip to main content
 首页 » 编程设计

python之如何从 Python 日志文件中删除额外数据

2025年04月02日16qq78292959

我有一个 Python 脚本,它使用 Requests 模块向我们的 API 发送请求,然后收到答案,解析它并说明是否一切正常。结果显示为“打印”。这是一个简单的例子:

for i in response: 
    if i in response_keys: 
        print('[Request_name] '+i+' is ok') 
    else: 
        print('[Request_name] Extra key ' +i+' in resronse) 

现在我需要将这些打印品记录到 ti 文件中。当我像这样使用日志记录模块时:

#Example without sending a request, just logging configuration and check 
import logging 
logging.basicConfig(filename='Autotests_log.log', level=logging.INFO, format='%(asctime)s %(message)s' ) 
 
 
for i in response: 
    if i in response_keys: 
        logging.info('[Request_name] '+i+' is ok') 
    else: 
        logging.info('[Request_name] '+i+' is not ok') 

我在日志文件中看到了这个:

2016-04-20 14:24:44,823 Starting new HTTP connection (1): 192.168.1.44 
2016-04-20 14:24:44,873 [Request_name] success is ok 
2016-04-20 14:24:44,874 [Request_name] statusCode is ok 
2016-04-20 14:24:44,874 [Request_name] data is ok 
2016-04-20 14:24:44,876 Starting new HTTP connection (1): 192.168.1.44 
2016-04-20 14:24:44,924 Starting new HTTP connection (1): 192.168.1.44 
2016-04-20 14:24:44,974 Starting new HTTP connection (1): 192.168.1.44 
2016-04-20 14:24:45,017 Starting new HTTP connection (1): 192.168.1.44 

我应该怎么做才能在日志中看到这个:

2016-04-20 14:24:44,873 [Request_name] success is ok 
2016-04-20 14:24:44,874 [Request_name] statusCode is ok 
2016-04-20 14:24:44,874 [Request_name] data is ok 

请您参考如下方法:

尝试配置请求日志级别

import logging 
logging.getLogger("requests").setLevel(logging.WARNING)