Python Requests 库在日志记录中抛出异常

标签 python python-2.7 logging python-requests urllib3

Python requests 库在记录行为方面似乎有一些相当奇怪的怪癖。 使用最新的 Python 2.7.8,我有以下代码:

import requests
import logging

logging.basicConfig(
    filename='mylog.txt',
    format='%(asctime)-19.19s|%(task)-36s|%(levelname)s:%(name)s: %(message)s',
    level=eval('logging.%s' % 'DEBUG'))

logger = logging.getLogger(__name__)

logger.info('myprogram starting up...', extra={'task': ''})     # so far so good
...
(ommited code)
...
payload = {'id': 'abc', 'status': 'ok'}

# At this point the program continues but throws an exception.
requests.get('http://localhost:9100/notify', params=payload) 

print 'Task is complete! NotifyURL was hit! - Exiting'

我的程序似乎正常退出,但是在它创建的日志文件 (mylog.txt) 中我总是发现以下异常:

KeyError: 'task'
Logged from file connectionpool.py, line 362

如果我删除它: requests.get('http://localhost:9100/notify', params=payload) 然后异常就消失了。

我到底做错了什么,我该如何解决? 我正在使用请求 v2.4.3。

最佳答案

问题出在您的自定义日志记录格式上,您希望在其中出现 %(task)。 Requests(或者更确切地说,捆绑的 urllib3)在记录日志时不包含 task 参数,因为它无法知道您期望的是什么。

关于Python Requests 库在日志记录中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26759577/

相关文章:

python - 为什么我的代码每次运行后都会从同一图像中的同一列表中找到更多对象?

python - 并行化python for循环

python - 查找数据子集上方和下方多行的有效方法

c# - 使用 AddTraceSource 的 dotnet 核心日志记录不起作用

ruby-on-rails - 从错误日志中删除 Assets 加载

python - 如何按顺序检索 firebase 数据

python - pyqt4从其他py文件绘制圆弧

python - 将 python 服务作为后台服务运行

python - 条件语句中多个 'or' 语句的有效方法

.net - Windows 窗体的未处理异常日志记录