登录

SANIC允许您根据 python3 logging API . 如果您想创建一个新的配置,那么您应该对python3日志记录有一些基本知识。

快速启动

使用默认设置的简单示例如下:

from sanic import Sanic
from sanic.log import logger
from sanic.response import text

app = Sanic('logging_example')

@app.route('/')
async def test(request):
    logger.info('Here is your log')
    return text('Hello World!')

if __name__ == "__main__":
  app.run(debug=True, access_log=True)

服务器运行后,您可以看到以下消息:

[2018-11-06 21:16:53 +0800] [24622] [INFO] Goin' Fast @ http://127.0.0.1:8000
[2018-11-06 21:16:53 +0800] [24667] [INFO] Starting worker [24667]

您可以向服务器发送请求,它将打印日志消息:

[2018-11-06 21:18:53 +0800] [25685] [INFO] Here is your log
[2018-11-06 21:18:53 +0800] - (sanic.access)[INFO][127.0.0.1:57038]: GET http://localhost:8000/  200 12

要使用自己的日志配置,只需使用 logging.config.dictConfig 或通过 log_config 初始化时 Sanic 应用程序:

app = Sanic('logging_example', log_config=LOGGING_CONFIG)

要关闭日志记录,只需分配access_log=false:

if __name__ == "__main__":
  app.run(access_log=False)

这将在处理请求时跳过调用日志记录函数。你甚至可以在生产中做更多的工作来获得额外的速度:

if __name__ == "__main__":
  # disable debug messages
  app.run(debug=False, access_log=False)

配置

默认情况下, log_config 参数设置为使用 sanic.log.LOGGING_CONFIG_DEFAULTS 配置字典。

Sanic 使用了三个 loggers如果要创建自己的日志配置,则必须定义

记录器名称

用例

sanic.root

用于记录内部消息。

sanic.error

用于记录错误日志。

sanic.access

用于记录访问日志。

日志格式:

除了python提供的默认参数之外 (asctimelevelnamemessage )SANIC为访问记录器提供了附加参数:

日志上下文参数

参数值

资料型态

host

request.ip

STR

request

request.method + " " + request.url

STR

status

response.status

int

byte

len(response.body)

int

默认访问日志格式为 %(asctime)s - (%(name)s)[%(levelname)s][%(host)s]: %(request)s %(message)s %(status)d %(byte)d