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.