Open Singlerq opened 1 year ago
Something like this:
cd examples/fastapi/
vi main.py
uvicorn main:app
Add some lines to main.py
# pylint: disable=E0611,E0401
+import logging
from typing import List
from fastapi import FastAPI, HTTPException
from models import User_Pydantic, UserIn_Pydantic, Users
from pydantic import BaseModel
+from tortoise.contrib import fastapi
from tortoise.contrib.fastapi import HTTPNotFoundError, register_tortoise
+fastapi.logger = logging.getLogger('uvicorn')
+
app = FastAPI(title="Tortoise ORM FastAPI example")
The logging will be:
INFO: Started server process [30978]
INFO: Waiting for application startup.
INFO: Tortoise-ORM started, {'default': <tortoise.backends.sqlite.client.SqliteClient object at 0x103aff340>}, {'models': {'Users': <class 'models.Users'>}}
INFO: Tortoise-ORM generating schema
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
这是来自QQ邮箱的假期自动回复邮件。 邮件已收!
an example here
import logging
import sys
def setup_logger(
name: str, level: LogLevel, debug_sql: bool = False
) -> logging.Logger:
log_group_name = f"/service/{name}"
print("setup_logger", level, level.name)
logging.basicConfig(level=level.value)
logger = logging.getLogger(name)
fmt = logging.Formatter(
fmt="%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
sh = logging.StreamHandler(sys.stdout)
sh.setLevel(level.value)
sh.setFormatter(fmt)
# will print debug sql
if debug_sql:
logger_db_client = logging.getLogger("db_client")
logger_db_client.setLevel(logging.DEBUG)
logger_db_client.addHandler(sh)
logger_tortoise = logging.getLogger("tortoise")
logger_tortoise.setLevel(logging.DEBUG)
logger_tortoise.addHandler(sh)
return logger
这是来自QQ邮箱的假期自动回复邮件。 邮件已收!
When i use fastapi with tortoise-orm, how to print sql log to console? I connect to MySQL, I use the optional config echo=true, but it is not useful?
TORTOISE_ORM = { "connections": { "default": { "engine": "tortoise.backends.mysql", "credentials": { "host": configs.MYSQL_SERVER, "port": configs.MYSQL_PORT, "user": configs.MYSQL_USER, "password": configs.MYSQL_PASSWORD, "database": configs.MYSQL_DB_NAME, "charset": configs.MYSQL_CHARSET, "echo": configs.MYSQL_ECHO, } } }, "apps": { "models": { "models": [ "aerich.models", "app.v1.models.__init__" ], "default_connection": "default", }, }, "use_tz": configs.MYSQL_USE_TZ, "timezone": configs.MYSQL_TIMEZONE, }