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

Jac*_*far 2 python logging python-3.x aiohttp

我正在将 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)
Run Code Online (Sandbox Code Playgroud)

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

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" 
Run Code Online (Sandbox Code Playgroud)

message组件有一个冗余时间戳,我想自定义其格式。该文件说,它应该是可能的,但我不明白如何使它实际工作,也没有代码示例。

我只发现了这种用法,但有:

mylogger = logging.Logger('aiohttp.access')
mylogger.setLevel(logging.DEBUG)
mylogger.addHandler(ch)

handler = app.make_handler(
        logger=mylogger,
        access_log_format='%r %s %b',
)
Run Code Online (Sandbox Code Playgroud)

该应用程序根本不产生任何日志。我不明白究竟make_handler是什么,之前的问题也无济于事。

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

小智 5

你可以看到我的样本:

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()
Run Code Online (Sandbox Code Playgroud)

运行它并访问“ http://127.0.0.1:8080/xmwd ”,您将GET /xmwd HTTP/1.1 200 11在控制台中看到。