在aiohttp 2中指定日志请求格式 [英] specify log request format in 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()
运行它并访问' http://127.0.0.1:8080/xmwd ',您将在您的控制台中看到GET /xmwd HTTP/1.1 200 11
.
run it and access 'http://127.0.0.1:8080/xmwd', you will see GET /xmwd HTTP/1.1 200 11
in your console.
这篇关于在aiohttp 2中指定日志请求格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!