我们要搭建日志系统,我们使用loguru,挺不错的一个开源的日志系统。可以使用
pip install loguru
我们在common创建log.py使用方式也很简单
import os
import time
from loguru import logger
#日志的路径
log_path = os.path.join(os.getcwd(), 'logs')
if not os.path.exists(log_path):
os.mkdir(log_path)
#日志输出的文件格式
log_path_error = os.path.join(log_path, f'{time.strftime("%Y-%m-%d")}_error.log')
logger.add(log_path_error, rotation="12:00", retention="5 days", enqueue=True)
我们看下如何使用
#首先去导入
from common.logs import logger
新建用户
@usersRouter.post("/users/", tags=["users"])
def create_user(user: UserCreate, db: Session = Depends(get_db)):
"""
- **email**: 用户的邮箱
- **password**: 用户密码
"""
logger.info("创建用户")
db_crest = get_user_emai(db, user.email)
user.password = get_password_hash(user.password)
if not db_crest:
logger.success("创建用户成功")
user=db_create_user(db=db, user=user)
return reponse(code=0,data={'user':user.email},message="success")
logger.error("账号:{}不能重复".format(user.email))
return reponse(data={'msg':"账号不能重复"},code=1,message="error")
要将它介绍到使用它的地方,我们可以直接开始。
[En]
To introduce it where it is used, we can just start it.
启动后,默认情况下会创建此文件
[En]
After startup, this file is created by default
我们看下请求的输出
根据您使用的类型,控制台中的输出会有所不同,相应日志的颜色也会有所不同。让我们来看看文件中的输出。
[En]
And the output in the console will vary according to the type you use, and the color of the corresponding log is also different. Let’s take a look at the output in the file.
它也以固定的格式输出给我们,包括我们输出哪一行,以及我们使用什么方法来方便我们的后续故障排除。
[En]
It is also output to us in a fixed format, including which line we output and what method we use to facilitate our follow-up troubleshooting.
代码存储https://gitee.com/liwanlei/fastapistuday
第一个帖子是在官方账号上。欢迎关注我们。
[En]
The first post is on the official account. Welcome to follow us.
Original: https://www.cnblogs.com/leiziv5/p/15416960.html
Author: 北漂的雷子
Title: FastAPI 学习之路(六十)打造系统的日志输出
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/510938/
转载文章受原作者版权保护。转载请注明原作者出处!