我正在将aiohttp 2与Python 3.6配合使用,并希望记录到应用程序的请求.
我做了:
# 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)
现在,当应用程序运行时,我会收到以下格式的日志:
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"
消息组件具有多余的时间戳,我想自定义其格式. documentation说应该有可能,但是我不明白如何使其真正起作用,也没有代码示例.
我发现只有this usage,但有:
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的确切功能,而previous question则无济于事.
如何格式化日志的消息部分并插入aiohttp文档中列出的元素?
解决方法:
您可以看到我的示例:
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.