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

时间:2016-04-20 08:52:41

标签: python logging python-requests

我有一个Python脚本,它使用Requests模块向我们的API发送请求,然后收到ansver,解析它并说“一切都好或不好”。结果显示为' print'。这是一个简单的例子:

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

现在我需要记录这些打印文件。当我像这样使用Logging模块时:

#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

1 个答案:

答案 0 :(得分:1)

尝试配置requests日志记录级别

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