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

标签 python python-3.x logging 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)

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

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 组件具有冗余时间戳,我想自定义其格式。 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没有帮助。

如何格式化日志的 message 部分并插入 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

关于python - 在aiohttp 2中指定日志请求格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43500983/

相关文章:

Python/OpenCV — 细菌图像中的智能质心跟踪?

python - 无法从某些元素中抓取特定项目

mysql - 记录 mysql 查询

android - Log.isLoggable 是否返回错误值?

python - 使用 Python 列出 Google Cloud Storage 存储桶

python - 使用名称从网站上抓取数据表

python - 将适用于 Python 的 Google App Engine SDK 与 Python 3 结合使用

python - 如何从这个 Pytorch 代码中找到 Keras 中使用的等效 'batch_size' ?

python - Django 返回 403 错误 - "CSRF cookie not set"

Python - mysql - 记录生成警告的查询