在 Gunicorn 中使用 aiohttp 和 aiopg 时如何设置日志记录?

jel*_*ola 7 python psycopg2 gunicorn aiohttp

aiohttp很棒,但是在本地和生产环境中使用Gunicorn.

我发现的大多数用于设置日志记录的示例和文档都用于在本机服务器模式下运行,您可以在其中使用 make_handler()

正如文档中所建议的,我将其Gunicorn用作 Web 服务器进行部署,因此我没有make_handler明确调用。

我没有看到 aiohttp.access 日志,也没有看到 aiohttp.server 日志,也没有看到 aiopg 日志,所有这些都应该默认设置

这是我在根级别得到的app.py

import logging

import aiopg
from aiohttp import web

async def some_handler(request):
    id = request.match_info["id"]
    # perform some SA query
    return web.json_response({"foo": id})

async def close_postgres(app):
    app['postgres'].close()
    await app['postgres'].wait_closed

async def init(loop, logger, config):
    app = web.Application(
        loop=loop,
        logger=logger
    )

    app['postgres'] = await aiopg.sa.create_engine(loop=loop, echo=True) # other args ommitted
    app.on_cleanup.append(close_postgres)

    app.router.add_route('GET', '/', some_handler, 'name')

    return app

def run():
    config = parse_yaml('config.yml') # => turns config.yml to dict
    logging.config.dictConfig(config['logging'])
    logger = logging.getLogger("api")

    loop = asyncio.get_event_loop()
    app = run_until_complete(init(loop, logger, config))

    return app
Run Code Online (Sandbox Code Playgroud)

我的 config.yml 文件

logging:
  version: 1
  formatters:
    simple:
      format: '[%(asctime)s] [%(process)d] [%(levelname)s] %(message)s'
      datefmt: '%Y-%m-%d %H:%M:%S %z'
  handlers:
    console:
      class: logging.StreamHandler
      formatter: simple
      level: DEBUG
      stream: ext://sys.stdout
  loggers:
    api:
      handlers:
        - console
      level: DEBUG
Run Code Online (Sandbox Code Playgroud)

我使用以下命令启动 gunicorn:

gunicorn 'app:run()' --worker-class aiohttp.worker.GunicornWebWorker
Run Code Online (Sandbox Code Playgroud)

无论我进行什么查询,我都只会看到以下日志:

[2016-08-22 11:26:46 -0400] [41993] [INFO] Starting gunicorn 19.6.0
[2016-08-22 11:26:46 -0400] [41993] [INFO] Listening at: http://127.0.0.1:8000 (41993)
[2016-08-22 11:26:46 -0400] [41993] [INFO] Using worker: aiohttp.worker.GunicornWebWorker
[2016-08-22 11:26:46 -0400] [41996] [INFO] Booting worker with pid: 41996
Run Code Online (Sandbox Code Playgroud)

我想要的是:

  • aiopg 日志(查询运行的)
  • 访问日志
  • 服务器日志

谢谢

And*_*lov 3

文档最终并不建议使用 Gunicorn 进行部署,但有在 Gunicorn 下运行的说明。

也许应该升级为访问记录器传递正确的格式。

从我的角度来看,运行 aiohttp 服务器的最简单方法就是运行它(通过使用web.run_app()处理程序或在其之上构建自己的运行程序)。

如果您需要多个 aiohttp 实例 - 在反向代理模式下使用 nginx(很可能您的工具链中已经有它)和supervisord 来控制服务器。

该组合无需中间层即可工作。就像人们开始龙卷风或扭曲一样。