网站首页 > 技术文章 正文
25.FastAPI日志处理
在软件开发过程中,日志处理是经常使用的,在FastAPI中,可以直接使用python的日志处理logging,但配置相对比较麻烦一点,推荐使用开源日志扩展库loguru。
25.1安装loguru
pip install loguru
相关文档: http://loguru.readthedocs.io/
25.2集成到FastAPI
在FastAPI项目下新建包common,在common包中新建logger.py,其内容如下:
# coding: utf-8
import os
from datetime import datetime
from loguru import logger
log_path = '/u01'
if not os.path.exists(log_path): os.mkdir(log_path)
log_file = '{0}/fa_25_{1}_log.log'.format(log_path, datetime.now().strftime('%Y-%m-%d'))
logger.add(log_file, rotation="12:00", retention="1 days", enqueue=True)
在上面代码中通过logger.add方法创建日志文件。具体创建日志文件的方式可以参考loguru相关文档。
25.3使用logger
在需要使用logger的时候,从common.logger中引入,然后使用logger中提供的info、error等方法输出信息。
代码示例:
# coding: utf-8
from fastapi import FastAPI
from common.logger import logger
app = FastAPI()
@app.get(path='/')
async def root():
logger.info('Hello world')
logger.info('日志测试。')
return "Hello world"
启动应用并多次执行请求,然后查看日志文件,其内容如下:
2022-02-07 17:42:00.220 | INFO | main:root:10 - Hello world
2022-02-07 17:42:00.224 | INFO | main:root:11 - 日志测试。
2022-02-07 17:42:01.004 | INFO | main:root:10 - Hello world
2022-02-07 17:42:01.008 | INFO | main:root:11 - 日志测试。
2022-02-07 17:42:01.747 | INFO | main:root:10 - Hello world
2022-02-07 17:42:01.750 | INFO | main:root:11 - 日志测试。
2022-02-07 17:42:02.496 | INFO | main:root:10 - Hello world
2022-02-07 17:42:02.498 | INFO | main:root:11 - 日志测试。
2022-02-07 17:42:03.175 | INFO | main:root:10 - Hello world
2022-02-07 17:42:03.179 | INFO | main:root:11 - 日志测试。
猜你喜欢
- 2024-12-29 基于 SLF4J 的 MDC 实现日志链路追踪详解
- 2024-12-29 使用Flume同步日志到Kafka flume收集日志到hdfs
- 2024-12-29 Python日志模块logging python logger日志级别
- 2024-12-29 在Spring Boot中通过AOP技术实现日志拦截操作
- 2024-12-29 [编程基础] Python日志记录库logging总结
- 2024-12-29 如何将日志记录到 Windows事件日志 中
- 2024-12-29 SpringBoot集成logback异步日志 springboot集成日志log4j2
- 2024-12-29 Spring Boot中的Logback日志配置详解
- 2024-12-29 Linux 系统日志写入记录命令用法(logger)
- 2024-12-29 Python logging模块日志相关功能及应用示例
- 05-16在实际操作过程中如何避免出现SQL注入漏洞
- 05-16MySQL中 in数量限制
- 05-16一文讲懂SQL筛选子句HAVING子句
- 05-16性能调优实战:Spring Boot 多线程处理SQL IN语句大量值的优化方案
- 05-16sqlserver数据库中的模糊查询like和通配符的使用
- 05-16SQL必备 和 表关联
- 05-16SQL Server优化50法
- 05-16他们一直都在!最新强军大片来了
- 最近发表
- 标签列表
-
- cmd/c (64)
- c++中::是什么意思 (83)
- 标签用于 (65)
- 主键只能有一个吗 (66)
- c#console.writeline不显示 (75)
- pythoncase语句 (81)
- es6includes (73)
- sqlset (64)
- windowsscripthost (67)
- apt-getinstall-y (86)
- node_modules怎么生成 (76)
- chromepost (65)
- c++int转char (75)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- & (66)
- java (73)
- org.redisson (64)
- js数组插入 (83)
- gormwherein (64)
- linux删除一个文件夹 (65)
- mac安装java (72)
- eacces (67)
- 查看mysql是否启动 (70)
- 无效的列索引 (74)