网站首页 > 技术文章 正文
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模块日志相关功能及应用示例
- 02-21走进git时代, 你该怎么玩?_gits
- 02-21GitHub是什么?它可不仅仅是云中的Git版本控制器
- 02-21Git常用操作总结_git基本用法
- 02-21为什么互联网巨头使用Git而放弃SVN?(含核心命令与原理)
- 02-21Git 高级用法,喜欢就拿去用_git基本用法
- 02-21Git常用命令和Git团队使用规范指南
- 02-21总结几个常用的Git命令的使用方法
- 02-21Git工作原理和常用指令_git原理详解
- 最近发表
- 标签列表
-
- cmd/c (57)
- c++中::是什么意思 (57)
- sqlset (59)
- ps可以打开pdf格式吗 (58)
- phprequire_once (61)
- localstorage.removeitem (74)
- routermode (59)
- vector线程安全吗 (70)
- & (66)
- java (73)
- org.redisson (64)
- log.warn (60)
- cannotinstantiatethetype (62)
- js数组插入 (83)
- resttemplateokhttp (59)
- gormwherein (64)
- linux删除一个文件夹 (65)
- mac安装java (72)
- reader.onload (61)
- outofmemoryerror是什么意思 (64)
- flask文件上传 (63)
- eacces (67)
- 查看mysql是否启动 (70)
- java是值传递还是引用传递 (58)
- 无效的列索引 (74)