Paw*_*ech 4 python python-3.x python-asyncio aiohttp python-3.5
我有一些代码向一些API发出请求序列.我想为所有人设置通用日志记录,我该如何设置它?
假设我的代码看起来像这样
import aiohttp
import asyncio
async def fetch(client):
async with client.get('http://httpbin.org/get') as resp:
assert resp.status == 200
return await resp.text()
async def post_data(client):
async with client.post('http://httpbin.org/post', data={'foo': 'bar'}) as resp:
assert resp.status == 200
return await resp.text()
async def main(loop):
async with aiohttp.ClientSession(loop=loop) as client:
html = await fetch(client)
print(html)
other_html = await post_data(client)
print(other_html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
Run Code Online (Sandbox Code Playgroud)
现在我想查看所有请求的状态代码,网址,标题和所有请求,因此日志中的输出如下所示:
2017-08-09 08:44:30 DEBUG (200) <GET http://httpbin.org/get>
2017-08-09 08:44:30 DEBUG (200) <POST http://httpbin.org/post>
Run Code Online (Sandbox Code Playgroud)
我知道我可以在每次请求后添加logger.log()调用,但这将是重复的.如果我有更多请求,我将不得不在调用logger.log的每个请求下编写重复的代码.似乎效率低下.
有一个aiohttp.client记录器,但没有详细说明如何设置它.
我正试图像这样设置它
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
logging.getLogger('aiohttp.client').addHandler(ch)
Run Code Online (Sandbox Code Playgroud)
但它不打印我想看到的信息(例如响应状态代码,url).
有没有办法实现我的需要?也许我可以从客户端订阅一些信号并在发送信号时记录一些消息?例如,有一些机制来订阅当客户端收到响应时发送的信号,然后记录消息吗?
apa*_*hev 18
在撰写本文时(11/2020),您应该使用aiohttp 的跟踪功能:
import asyncio
import logging
import aiohttp
async def on_request_start(session, context, params):
logging.getLogger('aiohttp.client').debug(f'Starting request <{params}>')
async def main():
logging.basicConfig(level=logging.DEBUG)
trace_config = aiohttp.TraceConfig()
trace_config.on_request_start.append(on_request_start)
async with aiohttp.ClientSession(trace_configs=[trace_config]) as session:
await session.get('https://google.com')
asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)
正如您在aiohttp的代码中看到的那样,aiohttp.client记录器不用于记录请求,但只有在响应中的cookie无效时才能记录警告 https://github.com/aio-libs/aiohttp/search? UTF8 =%E2%9C%93&q = client_logger&类型=
要记录您正在执行的每个请求,您需要创建一个可以执行所需操作的自定义ClientSession.就像是:
class LoggingClientSession(aiohttp.ClientSession):
def request(self, method, url, **kwargs):
logger.debug('Starting request <%s %r>', method, url)
return super().request(method, url, **kwargs)
Run Code Online (Sandbox Code Playgroud)
-
正如Jaanus在评论这里要注意的post,get...帮助者知道打电话ClientSession._request直接代替request.因此,覆盖后者将不会拦截使用短手助手进行的呼叫.
所以你可以:
覆盖_request而不是request在你的助手中
或确保您的代码从不使用get/ ...助手,并始终request直接调用.
或者也定义你的所有助手方法 LoggingClientSession
-
正如Romuald所说,_request现在是一个协程,所以用常规函数覆盖它不会在正确的时间记录.这是一个更新的例子:
class LoggingClientSession(aiohttp.ClientSession):
async def _request(self, method, url, **kwargs):
logger.debug('Starting request <%s %r>', method, url)
return await super()._request(method, url, **kwargs)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2410 次 |
| 最近记录: |