Skip to content

Commit 458d6d8

Browse files
committed
Logging
1 parent 1ac4f76 commit 458d6d8

5 files changed

Lines changed: 71 additions & 14 deletions

File tree

‎src/fastapi_app/app.py‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import os
21
import logging
2+
import os
33
import pathlib
44
from datetime import datetime
55

@@ -13,14 +13,14 @@
1313

1414
from .models import Restaurant, Review, engine
1515

16-
logging.basicConfig(level=logging.DEBUG)
17-
16+
# Setup logger and Azure Monitor:
17+
logger = logging.getLogger("app")
18+
logger.setLevel(logging.INFO)
1819
if os.getenv("APPLICATIONINSIGHTS_CONNECTION_STRING"):
1920
configure_azure_monitor()
2021

21-
print("Setting up FastAPI app...")
22-
logging.warning("From logging: Setting up FastAPI app...")
2322

23+
# Setup FastAPI app:
2424
app = FastAPI()
2525
parent_path = pathlib.Path(__file__).parent.parent
2626
app.mount("/mount", StaticFiles(directory=parent_path / "static"), name="static")
@@ -29,6 +29,7 @@
2929
# Use relative path for url_for, so that it works behind a proxy like Codespaces
3030
templates.env.globals["url_for"] = app.url_path_for
3131

32+
3233
# Dependency to get the database session
3334
def get_db_session():
3435
with Session(engine) as session:
@@ -37,8 +38,7 @@ def get_db_session():
3738

3839
@app.get("/", response_class=HTMLResponse)
3940
async def index(request: Request, session: Session = Depends(get_db_session)):
40-
print("root called")
41-
logging.warning("From logging: root called")
41+
logger.info("root called")
4242
statement = (
4343
select(Restaurant, func.avg(Review.rating).label("avg_rating"), func.count(Review.id).label("review_count"))
4444
.outerjoin(Review, Review.restaurant == Restaurant.id)
@@ -59,7 +59,7 @@ async def index(request: Request, session: Session = Depends(get_db_session)):
5959

6060
@app.get("/create", response_class=HTMLResponse)
6161
async def create_restaurant(request: Request):
62-
print("Request for add restaurant page received")
62+
logger.info("Request for add restaurant page received")
6363
return templates.TemplateResponse("create_restaurant.html", {"request": request})
6464

6565

@@ -68,7 +68,7 @@ async def add_restaurant(
6868
request: Request, restaurant_name: str = Form(...), street_address: str = Form(...), description: str = Form(...),
6969
session: Session = Depends(get_db_session)
7070
):
71-
print(f"name: {restaurant_name} address: {street_address} description: {description}")
71+
logger.info("name: %s address: %s description: %s", restaurant_name, street_address, description)
7272
restaurant = Restaurant()
7373
restaurant.name = restaurant_name
7474
restaurant.street_address = street_address

‎src/fastapi_app/models.py‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
import os
23
import typing
34
from datetime import datetime
@@ -6,12 +7,15 @@
67
from dotenv import load_dotenv
78
from sqlmodel import Field, SQLModel, create_engine
89

10+
logger = logging.getLogger("app")
11+
logger.setLevel(logging.INFO)
12+
913
sql_url = ""
1014
if os.getenv("WEBSITE_HOSTNAME"):
11-
print("Connecting to Azure PostgreSQL Flexible server based on AZURE_POSTGRESQL_CONNECTIONSTRING...")
15+
logger.info("Connecting to Azure PostgreSQL Flexible server based on AZURE_POSTGRESQL_CONNECTIONSTRING...")
1216
env_connection_string = os.getenv("AZURE_POSTGRESQL_CONNECTIONSTRING")
1317
if env_connection_string is None:
14-
print("Missing environment variable AZURE_POSTGRESQL_CONNECTIONSTRING")
18+
logger.info("Missing environment variable AZURE_POSTGRESQL_CONNECTIONSTRING")
1519
else:
1620
# Parse the connection string
1721
details = dict(item.split('=') for item in env_connection_string.split())
@@ -23,7 +27,7 @@
2327
)
2428

2529
else:
26-
print("Connecting to local PostgreSQL server based on .env file...")
30+
logger.info("Connecting to local PostgreSQL server based on .env file...")
2731
load_dotenv()
2832
POSTGRES_USERNAME = os.environ.get("DBUSER")
2933
POSTGRES_PASSWORD = os.environ.get("DBPASS")

‎src/gunicorn.conf.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
max_requests = 1000
44
max_requests_jitter = 50
55
log_file = "-"
6-
bind = "0.0.0.0:8000"
6+
bind = "0.0.0.0:8888"
77
workers = (multiprocessing.cpu_count() * 2) + 1
88

9-
worker_class = "uvicorn.workers.UvicornWorker"
9+
worker_class = "my_uvicorn_worker.MyUvicornWorker"
1010

1111
timeout = 600

‎src/my_uvicorn_worker.py‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
from uvicorn_worker import UvicornWorker
2+
3+
logconfig_dict = {
4+
"version": 1,
5+
"disable_existing_loggers": False,
6+
"formatters": {
7+
"default": {
8+
"()": "uvicorn.logging.DefaultFormatter",
9+
"format": "%(asctime)s - %(message)s",
10+
},
11+
"access": {
12+
"()": "uvicorn.logging.AccessFormatter",
13+
"format": "%(asctime)s - %(message)s",
14+
},
15+
},
16+
"handlers": {
17+
"default": {
18+
"formatter": "default",
19+
"class": "logging.StreamHandler",
20+
"stream": "ext://sys.stderr",
21+
},
22+
"access": {
23+
"formatter": "access",
24+
"class": "logging.StreamHandler",
25+
"stream": "ext://sys.stdout",
26+
},
27+
},
28+
"loggers": {
29+
"root": {
30+
"level": "INFO",
31+
"handlers": ["default"]
32+
},
33+
"uvicorn.error": {
34+
"level": "INFO",
35+
"handlers": ["default"],
36+
"propagate": False,
37+
},
38+
"uvicorn.access": {
39+
"level": "INFO",
40+
"handlers": ["access"],
41+
"propagate": False,
42+
},
43+
},
44+
}
45+
46+
class MyUvicornWorker(UvicornWorker):
47+
CONFIG_KWARGS = {
48+
"loop": "asyncio",
49+
"http": "auto",
50+
"lifespan": "off",
51+
"log_config": logconfig_dict
52+
}

‎src/pyproject.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ dependencies = [
77
"fastapi",
88
"jinja2",
99
"uvicorn[standard]",
10+
"uvicorn-worker",
1011
"python-multipart",
1112
"psycopg2",
1213
"sqlmodel",

0 commit comments

Comments
 (0)