这里主要介绍了如何使用 uvicorn 模块自带的日志模块进行日志的配置, 而不是重新自定义日志模块。这样做的好处是可以做到日志统一, fastAPI自己本身的日志会和自己定义的输出日志输出到一起
新建一个日志文件(.py)用于存储日志配置
import os
scriptPath = os.path.split(os.path.realpath(__file__))[0]
configs = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'()': 'uvicorn.logging.DefaultFormatter',
# 这里自定义了日志格式
'fmt': '[%(asctime)s][default][%(module)s][%(funcName)s][%(lineno)d][%(levelname)s]: %(message)s',
'use_colors': None
},
'access': {
'()': 'uvicorn.logging.AccessFormatter',
# 这里自定义了日志格式
'fmt': '[%(asctime)s][access][%(module)s][%(funcName)s][%(lineno)d][%(levelname)s]: %(client_addr)s "%(request_line)s" %(status_code)s',
}
},
'handlers': {
# 主日志分段写入对应文件
'default': {
'formatter': 'default',
'class': 'logging.handlers.TimedRotatingFileHandler',
'filename': os.path.join(scriptPath, "app.log"),
"when": "midnight",
"backupCount": 7,
"encoding": "utf-8",
},
# 访问日志分段写入对应文件
'access': {
'formatter': 'access',
'class': 'logging.handlers.TimedRotatingFileHandler',
'filename': os.path.join(scriptPath, "app.log"),
"when": "midnight",
"backupCount": 14,
"encoding": "utf-8",
},
# 控制台输出主日志
'default_console': {
'formatter': 'default',
'class': 'logging.StreamHandler',
'stream': 'ext://sys.stderr'
},
# 控制台输出访问日志
'access_console': {
'formatter': 'access',
'class': 'logging.StreamHandler',
'stream': 'ext://sys.stdout'
}
},
'loggers': {
'uvicorn': {
'handlers': ['default', 'default_console'], # 这里配置要用的handler: default是写入, console是输出到控制台
'level': 'INFO',
'propagate': False
},
'uvicorn.error': {'level': 'INFO'},
'uvicorn.access': {
'handlers': ['access', 'access_console'], # 这里配置要用的handler: default是写入, console是输出到控制台
'level': 'INFO',
'propagate': False
}
}
}
运行的时候调用配置
import uvicorn
# 使用自定义的 uvicorn 的日志配置文件
from server.logs import uvicornLogConfig
@app.get("/")
def helloWorld():
return 'hello world1'
if __name__ == '__main__':
uvicorn.run("main:app", host='0.0.0.0', log_config=uvicornLogConfig.configs)