前后端知识库 前后端知识库
首页
    • JavaScript
    • React
    • Vue
  • Python
  • Sanic
  • Linux
  • Ansible
归档
GitHub (opens new window)
首页
    • JavaScript
    • React
    • Vue
  • Python
  • Sanic
  • Linux
  • Ansible
归档
GitHub (opens new window)
  • Sanic

    • 开始
    • Routing
    • 请求数据
    • 响应
    • 静态资源
    • 异常
    • 中间件 和 监听器
    • 蓝图
    • WebSocket
    • 配置
    • Cookies
    • 处理装饰器
    • 流
    • 基于类的视图
    • 自定义协议
    • SSL 例子
    • 日志
      • 测试
      • 部署
      • 扩展
      • 贡献
      • API Reference
    • Python

    • backend
    • Sanic
    devin
    2023-09-07

    日志

    # 日志

    Sanic 允许你在基于 python3 logging API (opens new window) 的请求上做不同类型的日志 (access log, error log)。如果你想创建一个新的配置,你应该了解 python3 日志模块的基本知识。

    # 快速开始

    一个使用默认设置的简单例子如下:

    from sanic import Sanic
    
    app = Sanic('test')
    
    @app.route('/')
    async def test(request):
        return response.text('Hello World!')
    
    if __name__ == "__main__":
      app.run(debug=True, access_log=True)
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    要使用你自己的日志配置,简单使用 logging.config.dictConfig,或者在你初始化 Sanic 应用的时候传递 log_config:

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

    要关闭日志,只需指定 access_log=False:

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

    这会在处理请求时跳过调用日志记录程序。并且你甚至可以在生产中进一步提高速度:

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

    # 配置

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

    sanic 使用了三种 loggers,并且 当你想要创建你自己的日志配置时必须被定义:

    • root:
      用来记录内部消息。

    • sanic.error:
      用来记录错误日志。

    • sanic.access:
      用来记录访问日志。

    # 日志格式化:

    除了 python 提供的默认参数 (asctime, levelname, message) 外,Sanic 提供了额外的参数给访问日志:

    • host (str)
      request.ip

    • request (str)
      request.method + " " + request.url

    • status (int)
      response.status

    • byte (int)
      len(response.body)

    默认的访问日志格式如下:

    %(asctime)s - (%(name)s)[%(levelname)s][%(host)s]: %(request)s %(message)s %(status)d %(byte)d
    
    1
    编辑 (opens new window)
    上次更新: 2023/09/07, 12:09:00
    SSL 例子
    测试

    ← SSL 例子 测试→

    Theme by Vdoing | Copyright © 2023-2023 devin | MIT License
    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式