|
FastAPI学习-29uvicorn使用log_config参数设置logger日志格式FastAPI学习-29uvicorn使用log_config参数设置logger日志格式前言uvicorn的logging日志启动服务LOGGING_CONFIG日志默认格式log_config配置文件FastAPI学习-29uvicorn使用log_config参数设置logger日志格式前言FastAPI服务是通过uvicorn来提供的,日志都是uvicorn里配置的。官方文档地址:https://www.uvicorn.org/settings/#logginguvicorn的logging日志我们可以通过uvicorn.run()方式启动服务uvicorn.run("example:app",port=5000,reload=True,access_log=False)1于是可以加一些启动参数,与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-configCLI选项,则会忽略此选项。启动服务当我们启动服务,服务接口的时候,看到的日志是没有显示时间格式的fromfastapiimportFastAPIapp=FastAPI()@app.get("/demo/")asyncdefcreate_item():return{"demo":"helloworld"}if__name__=="__main__":importuvicornuvicorn.run(app='main:app',host="127.0.0.1",reload=True,port=8000,)123456789101112131415161718192021运行日志INFO:Willwatchforchangesinthesedirectories:['D:\\code\\fast_project\\xxx']INFO:Uvicornrunningonhttp://127.0.0.1:8000(PressCTRL+Ctoquit)INFO:Startedreloaderprocess[10924]usingStatReloadINFO:Startedserverprocess[5708]INFO:Waitingforapplicationstartup.INFO:Applicationstartupcomplete.INFO:127.0.0.1:5161-"GET/HTTP/1.1"404NotFoundINFO:127.0.0.1:5161-"GET/docsHTTP/1.1"200OKINFO:127.0.0.1:5161-"GET/demoHTTP/1.1"307TemporaryRedirectINFO:127.0.0.1:5161-"GET/demo/HTTP/1.1"200OK12345678910那么这些日志是从哪来的,又如何修改日志的默认格式呢?LOGGING_CONFIG日志默认格式LOGGING_CONFIG是uvicorn默认的日志配置fromuvicorn.configimportLOGGING_CONFIG1找到源码里面的配置内容如下LOGGING_CONFIGict[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},},}1234567891011121314151617181920212223242526272829303132我们可以通过修改"formatters"默认的日志格式,来控制日志输出的格式fromfastapiimportFastAPIfromuvicorn.configimportLOGGING_CONFIGLOGGING_CONFIG["formatters"]["default"]["fmt"]="%(asctime)s-%(levelprefix)s%(message)s"app=FastAPI()······12345678于是就可以看到启动的日志,前面加上了时间"%(asctime)s"2024-01-1609:49:04,408-INFO:Willwatchforchangesinthesedirectories:['D:\\code\\fast_project\\xxx']2024-01-1609:49:04,408-INFO:Uvicornrunningonhttp://127.0.0.1:8000(PressCTRL+Ctoquit)2024-01-1609:49:04,408-INFO:Startedreloaderprocess[9124]usingStatReload2024-01-1609:49:04,924-INFO:Startedserverprocess[11020]2024-01-1609:49:04,924-INFO:Waitingforapplicationstartup.2024-01-1609:49:04,924-INFO:Applicationstartupcomplete.123456访问http接口的日志通过修改"access"格式来控制fromfastapiimportFastAPIfromuvicorn.configimportLOGGING_CONFIGLOGGING_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()1234567log_config配置文件前面是通过修改LOGGING_CONFIG默认的参数来配置日志,我们也可以把配置文件单独写到一个uvicorn_config.json文件,加载本地配置文件覆盖默认的LOGGING_CONFIGuvicorn_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}}}123456789101112131415161718192021222324252627282930313233343536373839404142434445启动时导入配置文件fromfastapiimportFastAPIapp=FastAPI()@app.get("/demo/")asyncdefcreate_item():return{"demo":"helloworld"}if__name__=="__main__":importuvicornuvicorn.run(app='main:app',host="127.0.0.1",reload=True,port=8000,log_config="./uvicorn_config.json")1234567891011121314151617181920上海-悠悠FastAPI学习-29uvicorn使用log_config参数设置logger日志格式
|
|