在aiohttp 2中指定日志请求格式

编程入门 行业动态 更新时间:2024-10-25 14:26:23
本文介绍了在aiohttp 2中指定日志请求格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在将aiohttp 2与Python 3.6配合使用,并希望记录到应用程序的请求.

I'm using aiohttp 2 with Python 3.6 and want to log the requests coming to the application.

我做到了:

# use ISO timestamps from time import gmtime logging.Formatter.converter = gmtime # create a formatter ch = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(levelname)s %(name)s - %(message)s', '%Y-%m-%dT%H:%M:%S') ch.setFormatter(formatter) # show all emssages (default is WARNING) logging.getLogger('aiohttp.access').setLevel(logging.DEBUG) # attach the handler logging.getLogger('aiohttp.access').addHandler(ch)

现在在应用程序运行时,我会收到以下格式的日志:

and now when the application is running I get a log in this format:

2017-04-19T16:02:17 INFO aiohttp.access - 127.0.0.1 - - [19/Apr/2017:16:02:17 +0000] "GET /test HTTP/1.1" 404 547 "-" "curl/7.51.0"

message组件具有多余的时间戳,我想自定义其格式. 文档说应该可以,但我不知道该怎么做它确实有效,并且没有代码示例.

the message component has a redundant timestamp, and I'd like to customize its format. The documentation says it should be possible but I don't understand how to make it actually work and there are no code examples.

我仅发现此用法但具有:

mylogger = logging.Logger('aiohttp.access') mylogger.setLevel(logging.DEBUG) mylogger.addHandler(ch) handler = app.make_handler( logger=mylogger, access_log_format='%r %s %b', )

该应用程序根本不生成任何日志.我不明白make_handler到底能做什么,还有一个上一个问题没有帮助.

the application produces no log at all. I don't understand what make_handler does exactly, and a previous question doesn't help.

如何格式化日志的message部分并插入aiohttp文档中列出的元素?

How can I format the message part of the log and insert the elements listed in the aiohttp docs ?

推荐答案

您可以看到我的示例:

import asyncio import logging from aiohttp import web mylogger = logging.getLogger('aiohttp.access') mylogger.setLevel(logging.DEBUG) ch = logging.StreamHandler() mylogger.addHandler(ch) async def handle(request): name = request.match_info.get('name', "Anonymous") text = "Hello, " + name return web.Response(text=text) loop = asyncio.get_event_loop() app = web.Application(loop=loop) app.router.add_get('/', handle) app.router.add_get('/{name}', handle) loop.run_until_complete( loop.create_server( app.make_handler(access_log=mylogger, access_log_format='%r %s %b'), '0.0.0.0', 8080)) loop.run_forever() loop.close()

运行它并访问' 127.0.0.1:8080/xmwd ',您将在您的控制台中看到GET /xmwd HTTP/1.1 200 11.

run it and access '127.0.0.1:8080/xmwd', you will see GET /xmwd HTTP/1.1 200 11 in your console.

更多推荐

在aiohttp 2中指定日志请求格式

本文发布于:2023-11-23 10:29:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621111.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:格式   日志   aiohttp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!