Skip to content

Commit c7fea5e

Browse files
authored
Merge pull request #236 from minvws/logging-proeftuin
Added additional logging
2 parents 03b0532 + 112130b commit c7fea5e

21 files changed

Lines changed: 698 additions & 580 deletions

app/auth.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,17 @@ def get_auth_ctx(
5757
return ctx
5858

5959
if creds is None or creds.scheme.lower() != "bearer":
60-
logger.error("Missing or invalid bearer token")
60+
logger.error("missing or invalid bearer token")
6161
raise HTTPException(status_code=401, detail="Missing bearer token")
6262

6363
try:
6464
claims = client_oauth_service.verify(request)
6565
except OAuthError as e:
66-
logger.error(f"OAuth verification failed: {e.description}")
67-
raise HTTPException(status_code=e.status_code, detail=e.description) from e
66+
desc = getattr(e, "description", None) or str(e)
67+
status = getattr(e, "status_code", None) or 401
68+
69+
logger.exception("oauth verification failed (status=%s): %r", status, desc)
70+
raise HTTPException(status_code=status, detail="Invalid or unauthorized request") from e
6871

6972
ctx = AuthContext(
7073
claims=claims,

app/db/db.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,25 +23,25 @@ def __init__(self, dsn: str):
2323
else:
2424
self.engine = create_engine(dsn, echo=False)
2525
except BaseException as e:
26-
logger.error("Error while connecting to database: %s", e)
26+
logger.error("error while connecting to database: %s", e)
2727
raise e
2828

2929
def generate_tables(self) -> None:
30-
logger.info("Generating tables...")
30+
logger.info("generating tables...")
3131
Base.metadata.create_all(self.engine)
3232

3333
def truncate_tables(self) -> None:
34-
logger.info("Truncating all tables...")
34+
logger.info("truncating all tables...")
3535
try:
3636
metadata = MetaData()
3737
metadata.reflect(bind=self.engine)
3838
with Session(self.engine) as session:
3939
for table in reversed(metadata.sorted_tables):
4040
session.execute(text(f"DELETE FROM {table.name}"))
4141
session.commit()
42-
logger.info("All tables truncated successfully.")
42+
logger.info("all tables truncated successfully.")
4343
except Exception as e:
44-
logger.error("Error while truncating tables: %s", e)
44+
logger.error("error while truncating tables: %s", e)
4545
raise e
4646

4747
def is_healthy(self) -> bool:
@@ -55,7 +55,7 @@ def is_healthy(self) -> bool:
5555
session.execute(text("SELECT 1"))
5656
return True
5757
except Exception as e:
58-
logger.info("Database is not healthy: %s", e)
58+
logger.info("database is not healthy: %s", e)
5959
return False
6060

6161
def get_db_session(self) -> DbSession:

app/db/entities/base.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44

55

66
class Base(DeclarativeBase):
7+
"""
8+
Base class for all database entities.
9+
"""
710
def to_dict(self) -> Dict[str, Any]:
811
return {col.name: getattr(self, col.name) for col in self.__table__.columns}
912

app/db/entities/organization.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99

1010

1111
class Organization(Base):
12+
"""
13+
Represents an organization in the database.
14+
"""
1215
__tablename__ = "organization"
1316

1417
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)

app/db/entities/organization_key.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99

1010

1111
class OrganizationKey(Base):
12+
"""
13+
Represents a key associated with an organization in the database.
14+
"""
1215
__tablename__ = "organization_key"
1316

1417
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)

app/db/repositories/org_repository.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ def create(self, ura: str, name: str, max_usage_level: str) -> Organization:
3232
self.db_session.session.add(entry)
3333
self.db_session.session.flush()
3434

35+
logger.info("created organization with URA %s and name %r", ura, name)
3536
return entry
3637

3738
def update(self, org_id: uuid.UUID, name: str, max_usage_level: str) -> Optional[Organization]:
@@ -40,6 +41,7 @@ def update(self, org_id: uuid.UUID, name: str, max_usage_level: str) -> Optional
4041
"""
4142
org = self.get_by_id(org_id)
4243
if org is None:
44+
logger.error(f"organization with ID {org_id} does not exist")
4345
raise ValueError("Organization not found")
4446

4547
org.name = name # type: ignore
@@ -53,6 +55,7 @@ def delete(self, org_id: uuid.UUID) -> bool:
5355
"""
5456
org = self.get_by_id(org_id)
5557
if org is None:
58+
logger.error("organization with ID %s does not exist", org_id)
5659
return False
5760

5861
self.db_session.session.delete(org)

app/db/repositories/repository_base.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44

55

66
class RepositoryBase:
7+
"""
8+
Base class for all repositories, providing common functionality.
9+
"""
710
def __init__(self, db_session: session.DbSession):
811
self.db_session = db_session
912

app/db/session.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -129,21 +129,21 @@ def _retry(self, f: Callable[..., T], *args: Any, **kwargs: Any) -> T:
129129
try:
130130
return f(*args, **kwargs)
131131
except PendingRollbackError as e:
132-
logger.warning("Retrying operation due to PendingRollbackError: %s", e)
132+
logger.warning("retrying operation due to PendingRollbackError: %s", e)
133133
self.session.rollback()
134134
except OperationalError as e:
135-
logger.warning("Retrying operation due to OperationalError: %s", e)
135+
logger.warning("retrying operation due to OperationalError: %s", e)
136136
except DatabaseError as e:
137-
logger.warning("Retrying operation due to DatabaseError: %s", e)
137+
logger.warning("retrying operation due to DatabaseError: %s", e)
138138
raise e
139139
except Exception as e:
140-
logger.warning("Generic Exception during operation: %s", e)
140+
logger.warning("generic Exception during operation: %s", e)
141141
raise e
142142

143143
if len(backoff) == 0:
144-
logger.error("Operation failed after all retries")
144+
logger.error("operation failed after all retries")
145145
raise DatabaseError("Operation failed after all retries", None, BaseException())
146146

147-
logger.info("Retrying operation in %s seconds", backoff[0])
147+
logger.info("retrying operation in %s seconds", backoff[0])
148148
sleep(backoff[0] + random.uniform(0, 0.1))
149149
backoff = backoff[1:]

app/models/requests.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
from typing import Any, Literal, List
23

34
from pydantic import BaseModel, ConfigDict, model_validator, Field, field_validator
@@ -6,6 +7,7 @@
67
from app.services.pseudonym_service import PseudonymType
78
from app.rid import RidUsage
89

10+
logger = logging.getLogger(__name__)
911

1012
class RegisterRequest(BaseModel):
1113
scope: List[str]
@@ -18,6 +20,7 @@ class OrgRequest(BaseModel):
1820
@field_validator("ura")
1921
def ura_must_be_numbers(cls, v: Any) -> Any:
2022
if not v.isdigit():
23+
logger.warning("URA must contain only digits (got %s)", v)
2124
raise ValueError("URA must contain 8 digits")
2225
return v
2326

@@ -100,6 +103,7 @@ def validate_jwe(cls, data: dict[str, Any]) -> dict[str, Any]:
100103
# Check if JWE is actually a jwe token
101104
jwe_token = data.get("jwe")
102105
if not isinstance(jwe_token, str) or len(jwe_token.split('.')) != 5:
106+
logger.warning("invalid JWE token format: %s", jwe_token)
103107
raise ValueError("Invalid JWE token")
104108
return data
105109

@@ -108,6 +112,7 @@ def validate_jwe(cls, data: dict[str, Any]) -> dict[str, Any]:
108112
def validate_priv_key_pem(cls, data: dict[str, Any]) -> dict[str, Any]:
109113
priv_key_pem = data.get("priv_key_pem")
110114
if not isinstance(priv_key_pem, str) or not priv_key_pem.startswith("-----BEGIN PRIVATE KEY-----"):
115+
logger.warning("invalid private key PEM format")
111116
raise ValueError("Invalid private key PEM format")
112117
return data
113118

@@ -122,6 +127,7 @@ def validate_jwe(cls, data: dict[str, Any]) -> dict[str, Any]:
122127
# Check if JWE is actually a jwe token
123128
jwe_token = data.get("jwe")
124129
if not isinstance(jwe_token, str) or len(jwe_token.split('.')) != 5:
130+
logger.warning("invalid JWE token format: %s", jwe_token)
125131
raise ValueError("Invalid JWE token")
126132
return data
127133

@@ -130,5 +136,6 @@ def validate_jwe(cls, data: dict[str, Any]) -> dict[str, Any]:
130136
def validate_priv_key_pem(cls, data: dict[str, Any]) -> dict[str, Any]:
131137
priv_key_pem = data.get("priv_key_pem")
132138
if not isinstance(priv_key_pem, str) or not priv_key_pem.startswith("-----BEGIN PRIVATE KEY-----"):
139+
logger.warning("invalid private key PEM format")
133140
raise ValueError("Invalid private key PEM format")
134141
return data

app/routers/default.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def index() -> Response:
2828
content += "\nVersion: %s\nCommit: %s" % (data['version'], data['git_ref'])
2929
except BaseException as e:
3030
content += "\nNo version information found"
31-
logger.info("Version info could not be loaded: %s" % e)
31+
logger.info("version info could not be loaded: %s" % e)
3232

3333
return Response(content)
3434

@@ -39,7 +39,7 @@ def version_json() -> Response:
3939
with open(Path(__file__).parent.parent.parent / 'version.json', 'r') as file:
4040
content = file.read()
4141
except BaseException as e:
42-
logger.info("Version info could not be loaded: %s" % e)
42+
logger.info("version info could not be loaded: %s" % e)
4343
return Response(status_code=404)
4444

4545
return Response(content)

0 commit comments

Comments
 (0)