Skip to content

Commit 4a8d99d

Browse files
authored
Merge branch 'main' into mayank/amazon-ses-impl
2 parents 99a66e1 + 6c06f16 commit 4a8d99d

File tree

10 files changed

+86
-15
lines changed

10 files changed

+86
-15
lines changed

README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,18 @@ pdm run ruff format .
243243

244244
All code needs to pass ruff formatting and linting before it can be merged.
245245

246+
### Logging
247+
248+
To add a logger to a new service or file, use the `LOGGER_NAME` function in `app/utilities/constants.py`
249+
250+
```python
251+
from app.utilities.constants import LOGGER_NAME
252+
253+
log = logging.getLogger(LOGGER_NAME("my_service"))
254+
```
255+
256+
If you'd like to create a new logger name in the hierarchy, you'll need to add it to `alembic.ini` under the logger section. Following the pre-existing examples for `logger_uvicorn` for example.
257+
246258
### Frontend
247259

248260
#### Prettier

backend/README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,3 +136,15 @@ To apply the migration, run the following command:
136136
```bash
137137
pdm run alembic upgrade head
138138
```
139+
140+
### Logging
141+
142+
To add a logger to a new service or file, use the `LOGGER_NAME` function in `app/utilities/constants.py`
143+
144+
```python
145+
from app.utilities.constants import LOGGER_NAME
146+
147+
log = logging.getLogger(LOGGER_NAME("my_service"))
148+
```
149+
150+
If you'd like to create a new logger name in the hierarchy, you'll need to add it to `alembic.ini` under the logger section. Following the pre-existing examples for `logger_uvicorn` for example.

backend/alembic.ini

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ version_path_separator = os # Use os.pathsep. Default configuration used for ne
6262
# output_encoding = utf-8
6363

6464
# Updated in env.py using the POSTGRES_DATABASE_URL environment variable
65-
# sqlalchemy.url =
65+
# sqlalchemy.url =
6666

6767

6868
[post_write_hooks]
@@ -83,8 +83,10 @@ ruff.executable = %(here)s/.venv/bin/ruff
8383
ruff.options = check --fix REVISION_SCRIPT_FILENAME
8484

8585
# Logging configuration
86+
# Every time you want to define a new sub-logger, you need to add it to loggers or it won't show up.
87+
# Would recommend just using uvicorn."name of area you want to log" to identify a smaller scope
8688
[loggers]
87-
keys = root,sqlalchemy,alembic
89+
keys = root,sqlalchemy,alembic,uvicorn
8890

8991
[handlers]
9092
keys = console
@@ -107,12 +109,17 @@ level = INFO
107109
handlers =
108110
qualname = alembic
109111

112+
[logger_uvicorn]
113+
level = INFO
114+
handlers =
115+
qualname = uvicorn
116+
110117
[handler_console]
111118
class = StreamHandler
112119
args = (sys.stderr,)
113120
level = NOTSET
114121
formatter = generic
115122

116123
[formatter_generic]
117-
format = %(levelname)-5.5s [%(name)s] %(message)s
124+
format = %(levelname)-5.5s [%(name)s] %(message)s
118125
datefmt = %H:%M:%S

backend/app/models/__init__.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1+
import logging
2+
13
from alembic import command
24
from alembic.config import Config
35

6+
from app.utilities.constants import LOGGER_NAME
7+
48
# Make sure all models are here to reflect all current models
59
# when autogenerating new migration
610
from .Base import Base
@@ -10,8 +14,12 @@
1014
# Used to avoid import errors for the models
1115
__all__ = ["Base", "User", "Role"]
1216

17+
log = logging.getLogger(LOGGER_NAME("models"))
18+
1319

1420
def run_migrations():
21+
log.info("Running run_migrations in models/__init__ on server startup")
22+
1523
alembic_cfg = Config("alembic.ini")
1624
# Emulates `alembic upgrade head` to migrate up to latest revision
1725
command.upgrade(alembic_cfg, "head")

backend/app/server.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,24 @@
55
from dotenv import load_dotenv
66
from fastapi import FastAPI
77

8-
from app.routes import email_test
9-
108
load_dotenv()
119

1210
# we need to load env variables before initialization code runs
13-
from .routes import user # noqa: E402
11+
from . import models
12+
from .routes import send_email, user
13+
from .utilities.constants import LOGGER_NAME
14+
from .utilities.firebase_init import initialize_firebase
1415
from .utilities.ses.ses_init import ensure_ses_templates # noqa: E402
1516

16-
log = logging.getLogger("uvicorn")
17+
log = logging.getLogger(LOGGER_NAME("server"))
1718

1819

1920
@asynccontextmanager
2021
async def lifespan(_: FastAPI):
2122
log.info("Starting up...")
2223
ensure_ses_templates()
23-
# models.run_migrations()
24-
# initialize_firebase()
24+
models.run_migrations()
25+
initialize_firebase()
2526
yield
2627
log.info("Shutting down...")
2728

backend/app/services/implementations/user_service.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,13 @@
1212
UserCreateResponse,
1313
UserRole,
1414
)
15+
from app.utilities.constants import LOGGER_NAME
1516

1617

1718
class UserService(IUserService):
1819
def __init__(self, db: Session):
1920
self.db = db
20-
self.logger = logging.getLogger(__name__)
21+
self.logger = logging.getLogger(LOGGER_NAME("user_service"))
2122

2223
async def create_user(self, user: UserCreateRequest) -> UserCreateResponse:
2324
firebase_user = None

backend/app/utilities/constants.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
SERVER_LOGGER_NAME = "uvicorn"
2+
3+
4+
def LOGGER_NAME(name: str):
5+
return f"{SERVER_LOGGER_NAME}.{name}"
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,19 @@
1+
import logging
12
import os
23

34
import firebase_admin
45
from firebase_admin import credentials
56

7+
from app.utilities.constants import LOGGER_NAME
8+
9+
log = logging.getLogger(LOGGER_NAME("firebase_init"))
10+
611

712
def initialize_firebase():
13+
log.info("Running initialize_firebase")
814
cwd = os.getcwd()
915
service_account_path = os.path.join(cwd, "serviceAccountKey.json")
1016
cred = credentials.Certificate(service_account_path)
17+
1118
firebase_admin.initialize_app(cred)
19+
log.info("Finished initializing firebase")

backend/migrations/env.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
import os
23
from logging.config import fileConfig
34

@@ -9,27 +10,33 @@
910

1011
load_dotenv()
1112

13+
log = logging.getLogger("alembic")
14+
log.info("Entering env.py for alembic migration")
1215
# this is the Alembic Config object, which provides
1316
# access to the values within the .ini file in use.
1417
config = context.config
18+
log.info("Finished setting up alembic config object")
1519

1620
# Interpret the config file for Python logging.
1721
# This line sets up loggers basically.
1822
if config.config_file_name is not None:
19-
fileConfig(config.config_file_name)
23+
fileConfig(config.config_file_name, disable_existing_loggers=False)
2024

2125
# add your model's MetaData object here
2226
# for 'autogenerate' support
2327
# from myapp import mymodel
2428
# target_metadata = mymodel.Base.metadata
2529

30+
log.info("Pulling model metadata")
31+
2632
target_metadata = Base.metadata
2733

2834
# other values from the config, defined by the needs of env.py,
2935
# can be acquired:
3036
# my_important_option = config.get_main_option("my_important_option")
3137
# ... etc.
3238
config.set_main_option("sqlalchemy.url", os.environ["POSTGRES_DATABASE_URL"])
39+
log.info("Finished migration env config setup")
3340

3441

3542
def run_migrations_offline() -> None:
@@ -69,13 +76,19 @@ def run_migrations_online() -> None:
6976
prefix="sqlalchemy.",
7077
poolclass=pool.NullPool,
7178
)
79+
try:
80+
log.info("Established database connection")
81+
with connectable.connect() as connection:
82+
context.configure(connection=connection, target_metadata=target_metadata)
7283

73-
with connectable.connect() as connection:
74-
context.configure(connection=connection, target_metadata=target_metadata)
84+
with context.begin_transaction():
85+
context.run_migrations()
86+
log.info("Finished running migrations in alembic env")
87+
except Exception as e:
88+
log.error(e)
7589

76-
with context.begin_transaction():
77-
context.run_migrations()
7890

91+
log.info("Starting up migration env")
7992

8093
if context.is_offline_mode():
8194
run_migrations_offline()

backend/pyproject.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ distribution = false
3232
dev = "fastapi dev app/server.py"
3333
precommit = "pre-commit run"
3434
precommit-install = "pre-commit install"
35+
dc-down = "docker-compose down -v"
36+
dc-up = "docker-compose up -d"
37+
docker-db = {composite = ["dc-down", "dc-up"]}
38+
db-dev = {composite = ["docker-db", "dev"]}
3539
revision = "alembic revision --autogenerate"
3640
upgrade = "alembic upgrade head"
3741
tests = "pytest -v"

0 commit comments

Comments
 (0)