阿吉的Sanic教程--03日志的配置

3. 日志文件

你的鼓励是我前进的动力,请为我点个赞吧!

Sanic框架中的日志模块是基于python3 的logging的,开发者可以为其配置不同的方式。开发者也可以进行自定义设置,本小节不涉及此内容。

(1) 快捷配置

使用Sanic的默认配置。

from sanic import Sanic
from sanic.log import logger
from sanic.response import text
app = Sanic('test')
@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

开发者可以在创建app应用时使用logging.config.dictConfig或log_config自定义日志配置,具体代码如下所示:

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

关闭日志的使用,可以关闭设置access_log=False:

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

此方法将会跳过调用日志函数,开发者可以做额外的工作提sanic的运行速度

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

(2) 配置

默认情况下,sainc的配置一般使用log_config参数一般使用sanic.log.LOGGING_CONFIG_DEFAULTS的配置字典。sainc框架包含3种日志等级,如果开发者想要自定义配置,必须自己定义具体如下表所示:

日志标示 使用说明
sainc.root 用于记录网络日志
sainc.error 用于记录错误日志
sainc.access 用于记录访问日志

(3) 日志格式

python提供默认添加默认参数的方法[python(asctime,levename,message)],sainc提供登陆日志参数的功能:

日志上下文参数 参数 数据类型
host request.ip str
request request.method +””+request.url str
statues request.status int
byte len(response.body) int

默认登陆日志的格式如下所示:

%(asctime)s-(%(name)s)[%(levelname)s][%(host)s]:%(request)s%(message)s%(status)d%(byte)d
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章