Skip to content

Commit 25da936

Browse files
authored
Merge pull request #96 from pgulb/24-improve-api-logging
24 improve api logging
2 parents 5ddf316 + 0f8613e commit 25da936

File tree

5 files changed

+57
-9
lines changed

5 files changed

+57
-9
lines changed

api/Dockerfile

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
FROM python:3.12.6-slim-bookworm
22
WORKDIR /src
3+
COPY log_conf.yaml ./
34
COPY requirements.txt .
45
RUN pip install -r requirements.txt --no-cache-dir
56
COPY *.py ./
67
USER 1000:1000
7-
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "6789"]
8+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "6789", "--log-config=log_conf.yaml"]

api/Dockerfile-hot-reload

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@ RUN apt-get update && apt-get install netcat-traditional -y && rm -rf /var/lib/a
44
COPY requirements.txt .
55
RUN pip install -r requirements.txt --no-cache-dir
66
USER 1000:1000
7-
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "6789", "--reload"]
7+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "6789", "--reload", "--log-config=log_conf.yaml"]

api/log_conf.yaml

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
version: 1
2+
disable_existing_loggers: False
3+
formatters:
4+
default:
5+
# "()": uvicorn.logging.DefaultFormatter
6+
format: '%(levelname)s - %(asctime)s - %(name)s - %(message)s'
7+
access:
8+
# "()": uvicorn.logging.AccessFormatter
9+
format: '%(levelname)s - %(asctime)s - %(name)s - %(message)s'
10+
handlers:
11+
default:
12+
formatter: default
13+
class: logging.StreamHandler
14+
stream: ext://sys.stderr
15+
access:
16+
formatter: access
17+
class: logging.StreamHandler
18+
stream: ext://sys.stdout
19+
loggers:
20+
uvicorn.error:
21+
level: INFO
22+
handlers:
23+
- default
24+
propagate: no
25+
uvicorn.access:
26+
level: INFO
27+
handlers:
28+
- access
29+
propagate: no
30+
root:
31+
level: INFO
32+
handlers:
33+
- default
34+
propagate: no

api/main.py

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,20 +36,20 @@
3636
)
3737
security = HTTPBasic()
3838

39-
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(asctime)s %(message)s")
39+
logger = logging.getLogger(__name__)
4040
logging.getLogger("passlib").setLevel(logging.ERROR)
4141

4242
mongo_setting = os.getenv("MONGO_URL")
4343
if mongo_setting is None:
4444
raise ValueError("MONGO_URL not set")
4545
if mongo_setting == "mock":
4646
client = create_mock_client()
47-
logging.info("Using mock client")
47+
logger.info("Using mock client")
4848
else:
4949
client = create_mongo_client(mongo_setting)
50-
logging.info("Using mongo client")
50+
logger.info("Using mongo client")
5151
if "/?" in mongo_setting:
52-
logging.info(f"client options: {mongo_setting.split('/?')[1]}")
52+
logger.info(f"client options: {mongo_setting.split('/?')[1]}")
5353

5454

5555
def raise_basic_exception():
@@ -107,6 +107,7 @@ def readyz():
107107
try:
108108
client.admin.command("ping")
109109
except Exception:
110+
logger.error("mongodb ping failed")
110111
return Response("NOT OK", status_code=status.HTTP_503_SERVICE_UNAVAILABLE)
111112
return "OK"
112113

@@ -125,6 +126,7 @@ def create_user(user: User):
125126
}
126127
)
127128
except pymongo.errors.DuplicateKeyError as e:
129+
logger.error("User already exists")
128130
raise HTTPException(
129131
status_code=status.HTTP_409_CONFLICT, detail="User already exists"
130132
) from e
@@ -140,11 +142,14 @@ def delete_user(credentials: HTTPBasicCredentials = Depends(security)):
140142
try:
141143
flushes.delete_many({"user_id": credentials.username})
142144
if flushes.count_documents({"user_id": credentials.username}) > 0:
145+
logger.error("user still has flushes in mongodb")
143146
raise Exception("Error while flush deletion")
144147
result = users.delete_one({"_id": credentials.username})
145148
if result.deleted_count != 1:
149+
logger.error("mongodb responded with deleted_count != 1")
146150
raise Exception("User not deleted")
147151
except Exception as e:
152+
logger.error(f"error while deleting account - {e}")
148153
raise HTTPException(
149154
status_code=status.HTTP_400_BAD_REQUEST,
150155
detail="Error while deleting account",
@@ -176,6 +181,7 @@ def create_update_flush(
176181
if result.matched_count == 1:
177182
return Response(flush.time_start, status_code=status.HTTP_200_OK)
178183
except Exception as e:
184+
logger.error(f"error adding flush - {e}")
179185
raise HTTPException(
180186
status_code=status.HTTP_400_BAD_REQUEST, detail="Error adding flush"
181187
) from e
@@ -191,8 +197,10 @@ def delete_flush(
191197
try:
192198
result = flushes.delete_one(filter=filter_from_flush(credentials, flush))
193199
if result.deleted_count != 1:
200+
logger.error("flush not deleted - deleted_count != 1")
194201
raise Exception("Flush not deleted")
195202
except Exception as e:
203+
logger.error(f"error deleting flush - {e}")
196204
raise HTTPException(
197205
status_code=status.HTTP_400_BAD_REQUEST, detail="Error deleting flush"
198206
) from e
@@ -210,8 +218,10 @@ def delete_flush_by_id(
210218
filter=filter_from_creds_and_id(credentials, flush_id)
211219
)
212220
if result.deleted_count != 1:
221+
logger.error("flush not deleted by id - deleted_count != 1")
213222
raise Exception("Flush not deleted")
214223
except Exception as e:
224+
logger.error(f"error deleting flush by id - {e}")
215225
raise HTTPException(
216226
status_code=status.HTTP_400_BAD_REQUEST, detail="Error deleting flush"
217227
) from e
@@ -288,9 +298,7 @@ def get_flushes(
288298
e["time_end"] = e["time_end"].isoformat()
289299
return flushes_response(entries, credentials.username, skip)
290300
except Exception as e:
291-
logging.error(e)
292-
logging.info(type(entries))
293-
logging.info(entries)
301+
logger.error(f"error getting flushes - {e}")
294302
raise HTTPException(
295303
status_code=status.HTTP_400_BAD_REQUEST, detail="Error getting flushes"
296304
) from e
@@ -314,8 +322,10 @@ def update_password(
314322
)
315323
if result.matched_count == 1:
316324
return Response(status_code=status.HTTP_200_OK)
325+
logger.error(f"pass_change matched_count == {result.matched_count}")
317326
raise Exception(f"matched_count == {result.matched_count}")
318327
except Exception as e:
328+
logger.error(f"error changing password - {e}")
319329
raise HTTPException(
320330
status_code=status.HTTP_400_BAD_REQUEST, detail="Error changing password"
321331
) from e
@@ -383,6 +393,7 @@ def get_flush_stats(credentials: HTTPBasicCredentials = Depends(security)):
383393
del json_stats["_id"]
384394
return json_stats
385395
except Exception as e:
396+
logger.error(f"error getting stats - {e}")
386397
raise HTTPException(
387398
status_code=status.HTTP_400_BAD_REQUEST, detail="Error getting stats"
388399
) from e
@@ -404,6 +415,7 @@ def give_feedback(
404415
)
405416
return Response(status_code=status.HTTP_201_CREATED)
406417
except Exception as e:
418+
logger.error(f"error giving feedback - {e}")
407419
raise HTTPException(
408420
status_code=status.HTTP_400_BAD_REQUEST, detail="Error giving feedback"
409421
) from e

api/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ pymongo==4.10.1
2121
pytest==8.3.3
2222
python-dateutil==2.9.0.post0
2323
pytz==2024.2
24+
pyyaml==6.0.2
2425
sentinels==1.0.0
2526
six==1.16.0
2627
sniffio==1.3.1

0 commit comments

Comments
 (0)