aiohttp路由器-不写入日志

时间:2018-10-16 09:56:45

标签: python logging aiohttp

我有一个aiohttp网络应用,该应用使用路由作为装饰器和gunicorn之类的烧瓶

我在使日志正常工作方面遇到一些麻烦。

我在这里想念什么?

没有引发或记录错误,并且应用程序运行平稳,但是除了启动日志外,没有任何记录:

[2018-10-16 09:41:18 +0000] [1] [INFO] Starting gunicorn 19.9.0
[2018-10-16 09:41:18 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1)
[2018-10-16 09:41:18 +0000] [1] [INFO] Using worker: aiohttp.worker.GunicornWebWorker
[2018-10-16 09:41:18 +0000] [16] [INFO] Booting worker with pid: 16
[2018-10-16 09:41:18 +0000] [17] [INFO] Booting worker with pid: 17
[2018-10-16 09:41:18 +0000] [18] [INFO] Booting worker with pid: 18
[2018-10-16 09:41:18 +0000] [19] [INFO] Booting worker with pid: 19
[2018-10-16 09:41:18 +0000] [20] [INFO] Booting worker with pid: 20
[2018-10-16 09:41:18 +0000] [21] [INFO] Booting worker with pid: 21
[2018-10-16 09:41:18 +0000] [22] [INFO] Booting worker with pid: 22
[2018-10-16 09:41:18 +0000] [23] [INFO] Booting worker with pid: 23

我的app / init.py文件是这样的:

import logging
import os
from logging import handlers
from aiohttp.web import Application
from app.routes import routes
from utils.logging import CloggerFormatter

def create_app(app_config):
    app = Application()
    logger = logging.getLogger('aiohttp.web')

    log_level = logging.DEBUG

    if os.environ.get('LOG_LEVEL'):
        log_level = os.environ['LOG_LEVEL']

    app.router.add_routes(routes)
    logger.setLevel(log_level)
    logger.addHandler(CloggerFormatter)

    app['config'] = app_config

    return app

然后在我的app / routes.py文件中,使用request.app.logger从路由定义中访问记录器,例如:

from aiohttp.web import Response, RouteTableDef

routes = RouteTableDef()

@routes.post('/background-checks')
async def api_background_check(request):
    request_identifier = request.headers.get('X-Request-ID')

    if not request_identifier:
        request_identifier = uuid.uuid4()

    request.app.logger.info('Checking background for request: %s', request_identifier)

这是我的utils / handlers / logging.py文件:

from time import strftime, gmtime
from logging import Formatter

class CloggerFormatter(Formatter):
    """
    Logging module formatter in accordance with the yoti clogger manual
    guidelines.
    """
    converter = gmtime

    def __init__(self, datefmt=None):
        fmt = ('level:%(levelname)s'
               '\ttime:%(asctime)s'
               '\tmessage:%(message)s')

        Formatter.__init__(self, fmt=fmt, datefmt=datefmt)

    def formatTime(self, record, datefmt=None):
        """
        Return the creation time of the LogRecord using the RFC 3339
        format if datefmt is not specified.
        """
        ct = self.converter(record.created)
        if datefmt:
            s = strftime(datefmt, ct)
        else:
            t = strftime('%Y-%m-%dT%H:%M:%S', ct)
            s = '%s.%03dZ' % (t, record.msecs)
        return s

1 个答案:

答案 0 :(得分:0)

请使用root aiohttp记录器:logger = logging.getLogger('aiohttp')

尤其是访问记录器使用'aiohttp.access'名称,但也许您还希望查看其他日志消息,例如错误和警告。