FastAPI学习-29 uvicorn 使用 log_config 参数设置 logger 日志格式

前言

FastAPI 服务是通过 uvicorn 来提供的,日志都是 uvicorn 里配置的。
官方文档地址:https://www.uvicorn.org/settings/#logging

uvicorn 的 logging 日志

我们可以通过 uvicorn.run() 方式启动服务

uvicorn.run("example:app", port=5000, reload=True, access_log=False)

于是可以加一些启动参数,与logging 日志相关的几个参数:

** --log-config<path> 日志配置文件。**
选项:dictConfig()格式:.json、.yaml。任何其他格式都将使用fileConfig()处理。
设置formatters.default.use_colors和formatters.access.use_cors值以覆盖自动检测的行为。
如果您希望在日志配置中使用YAML文件,则需要将PyYAML作为项目的依赖项,或者安装带有[标准]可选附加功能的uvicorn。

--log-level<str> 置日志级别。
选项:'critical', 'error', 'warning', 'info', 'debug', 'trace'。默认值:'info'。

--no-access-log 仅禁用访问日志,不更改日志级别。

--use-colors/--no-use-colorss-启用/禁用日志记录的彩色格式,如果未设置此选项,则会自动检测到。如果使用--log-config CLI选项,则会忽略此选项。

启动服务

当我们启动服务,服务接口的时候,看到的日志是没有显示时间格式的

from fastapi import FastAPI

# 作者-上海悠悠 微信/QQ交流:283340479
# blog地址 https://www.cnblogs.com/yoyoketang/


app = FastAPI()


@app.get("/demo/")
async def create_item():
    return {"demo": "hello world"}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        app='main:app',
        host="127.0.0.1",
        reload=True,
        port=8000,
    )

运行日志

INFO:     Will watch for changes in these directories: ['D:\\code\\fast_project\\xxx']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [10924] using StatReload
INFO:     Started server process [5708]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     127.0.0.1:5161 - "GET / HTTP/1.1" 404 Not Found
INFO:     127.0.0.1:5161 - "GET /docs HTTP/1.1" 200 OK
INFO:     127.0.0.1:5161 - "GET /demo HTTP/1.1" 307 Temporary Redirect
INFO:     127.0.0.1:5161 - "GET /demo/ HTTP/1.1" 200 OK

那么这些日志是从哪来的,又如何修改日志的默认格式呢?

LOGGING_CONFIG 日志默认格式

LOGGING_CONFIG 是uvicorn默认的日志配置

from uvicorn.config import LOGGING_CONFIG

找到源码里面的配置内容如下

LOGGING_CONFIG: Dict[str, Any] = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "default": {
            "()": "uvicorn.logging.DefaultFormatter",
            "fmt": "%(levelprefix)s %(message)s",
            "use_colors": None,
        },
        "access": {
            "()": "uvicorn.logging.AccessFormatter",
            "fmt": '%(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s',  # noqa: E501
        },
    },
    "handlers": {
        "default": {
            "formatter": "default",
            "class": "logging.StreamHandler",
            "stream": "ext://sys.stderr",
        },
        "access": {
            "formatter": "access",
            "class": "logging.StreamHandler",
            "stream": "ext://sys.stdout",
        },
    },
    "loggers": {
        "uvicorn": {"handlers": ["default"], "level": "INFO", "propagate": False},
        "uvicorn.error": {"level": "INFO"},
        "uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False},
    },
}

我们可以通过修改"formatters"默认的日志格式,来控制日志输出的格式

from fastapi import FastAPI
from uvicorn.config import LOGGING_CONFIG

LOGGING_CONFIG["formatters"]["default"]["fmt"] = "%(asctime)s - %(levelprefix)s %(message)s"

app = FastAPI()

······

于是就可以看到启动的日志,前面加上了时间"%(asctime)s"

2024-01-16 09:49:04,408 - INFO:     Will watch for changes in these directories: ['D:\\code\\fast_project\\xxx']
2024-01-16 09:49:04,408 - INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
2024-01-16 09:49:04,408 - INFO:     Started reloader process [9124] using StatReload
2024-01-16 09:49:04,924 - INFO:     Started server process [11020]
2024-01-16 09:49:04,924 - INFO:     Waiting for application startup.
2024-01-16 09:49:04,924 - INFO:     Application startup complete.

访问 http 接口的日志通过修改"access"格式来控制

from fastapi import FastAPI
from uvicorn.config import LOGGING_CONFIG

LOGGING_CONFIG["formatters"]["default"]["fmt"] = "%(asctime)s - %(levelprefix)s %(message)s"
LOGGING_CONFIG["formatters"]["access"]["fmt"] = "%(asctime)s - %(levelprefix)s %(client_addr)s - \"%(request_line)s\" %(status_code)s"

app = FastAPI()

log_config 配置文件

前面是通过修改LOGGING_CONFIG 默认的参数来配置日志,我们也可以把配置文件单独写到一个uvicorn_config.json文件,加载本地配置文件覆盖默认的LOGGING_CONFIG
uvicorn_config.json

{
  "version": 1,
  "disable_existing_loggers": false,
  "formatters": {
    "default": {
      "()": "uvicorn.logging.DefaultFormatter",
      "fmt": "%(asctime)s - %(levelprefix)s %(message)s",
      "use_colors": null
    },
    "access": {
      "()": "uvicorn.logging.AccessFormatter",
      "fmt": "%(asctime)s - %(levelprefix)s %(client_addr)s - \"%(request_line)s\" %(status_code)s"
    }
  },
  "handlers": {
    "default": {
      "formatter": "default",
      "class": "logging.StreamHandler",
      "stream": "ext://sys.stderr"
    },
    "access": {
      "formatter": "access",
      "class": "logging.StreamHandler",
      "stream": "ext://sys.stdout"
    }
  },
  "loggers": {
    "uvicorn": {
      "handlers": [
        "default"
      ],
      "level": "INFO"
    },
    "uvicorn.error": {
      "level": "INFO"
    },
    "uvicorn.access": {
      "handlers": [
        "access"
      ],
      "level": "INFO",
      "propagate": false
    }
  }
}

启动时导入配置文件

from fastapi import FastAPI
# 作者-上海悠悠 微信/QQ交流:283340479
# blog地址 https://www.cnblogs.com/yoyoketang/

app = FastAPI()


@app.get("/demo/")
async def create_item():
    return {"demo": "hello world"}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        app='main:app',
        host="127.0.0.1",
        reload=True,
        port=8000,
        log_config="./uvicorn_config.json"
    )
posted @ 2024-01-16 10:34  上海-悠悠  阅读(3947)  评论(0编辑  收藏  举报