fastapi sqlalchemy.orm显示查询数据库日志
时间: 2023-07-16 19:17:11 浏览: 298
SqlAlchemy教程+学习文档
要在 FastAPI 和 SQLAlchemy ORM 中显示查询数据库的日志,可以按照以下步骤进行配置:
1. 在 FastAPI 应用程序中定义一个日志记录器(logger):
```python
import logging
logger = logging.getLogger("sqlalchemy.engine")
```
2. 在 SQLAlchemy 中启用日志记录器:
```python
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False},
# 日志记录器添加到配置中
logging_name="sqlalchemy.engine",
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
```
3. 设置日志记录级别和格式:
```python
logging.basicConfig(level=logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
```
现在,当你在应用程序中执行 SQL 查询时,将显示相应的日志消息。例如:
```python
from fastapi import FastAPI
from sqlalchemy.orm import Session
app = FastAPI()
@app.get("/items")
async def read_items(db: Session = Depends(get_db)):
logger.info("Retrieving items from database.")
items = db.query(Item).all()
return items
```
这将产生类似于以下内容的日志消息:
```
2022-01-01 12:00:00,000 - sqlalchemy.engine - INFO - Retrieving items from database.
2022-01-01 12:00:01,000 - sqlalchemy.engine - DEBUG - SELECT items.id AS items_id, items.title AS items_title, items.description AS items_description FROM items
```
这是一个基本的示例,你可以根据需要进行自定义和扩展。
阅读全文