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

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

I did:

# 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"

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.

I found only this usage but with:

mylogger = logging.Logger('aiohttp.access')

mylogger.setLevel(logging.DEBUG)

mylogger.addHandler(ch)

handler = app.make_handler(

logger=mylogger,

access_log_format='%r %s %b',

)

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

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

解决方案

You can see my sample:

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 it and access 'http://127.0.0.1:8080/xmwd', you will see GET /xmwd HTTP/1.1 200 11 in your console.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值