Skip to content

Commit 21dc457

Browse files
authored
Added logs for User and Creds Endpoint (#322)
* logs for cred * logs for user and utils * log id instead of email * precommit * structure logs to [function_name] Message | param1: value1, param2: value2 * pre commit * fix logs in crud * pre commit * change attempt to attempting
1 parent f24f4c5 commit 21dc457

7 files changed

Lines changed: 97 additions & 13 deletions

File tree

backend/app/api/routes/credentials.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import logging
2+
13
from fastapi import APIRouter, Depends
24

35
from app.api.deps import SessionDep, get_current_user_org_project
@@ -14,6 +16,7 @@
1416
from app.core.providers import validate_provider
1517
from app.core.exception_handlers import HTTPException
1618

19+
logger = logging.getLogger(__name__)
1720
router = APIRouter(prefix="/credentials", tags=["credentials"])
1821

1922

@@ -40,6 +43,9 @@ def create_new_credential(
4043
project_id=_current_user.project_id,
4144
)
4245
if existing_cred:
46+
logger.warning(
47+
f"[create_new_credential] Credentials for provider already exist | organization_id: {_current_user.organization_id}, project_id: {_current_user.project_id}, provider: {provider}"
48+
)
4349
raise HTTPException(
4450
status_code=400,
4551
detail=(
@@ -56,7 +62,10 @@ def create_new_credential(
5662
project_id=_current_user.project_id,
5763
)
5864
if not created_creds:
59-
raise Exception(status_code=500, detail="Failed to create credentials")
65+
logger.error(
66+
f"[create_new_credential] Failed to create credentials | organization_id: {_current_user.organization_id}, project_id: {_current_user.project_id}"
67+
)
68+
raise HTTPException(status_code=500, detail="Failed to create credentials")
6069

6170
return APIResponse.success_response([cred.to_public() for cred in created_creds])
6271

@@ -78,6 +87,9 @@ def read_credential(
7887
project_id=_current_user.project_id,
7988
)
8089
if not creds:
90+
logger.error(
91+
f"[read_credential] No credentials found | organization_id: {_current_user.organization_id}, project_id: {_current_user.project_id}"
92+
)
8193
raise HTTPException(status_code=404, detail="Credentials not found")
8294

8395
return APIResponse.success_response([cred.to_public() for cred in creds])
@@ -121,6 +133,9 @@ def update_credential(
121133
_current_user: UserProjectOrg = Depends(get_current_user_org_project),
122134
):
123135
if not creds_in or not creds_in.provider or not creds_in.credential:
136+
logger.error(
137+
f"[update_credential] Invalid input | organization_id: {_current_user.organization_id}, project_id: {_current_user.project_id}"
138+
)
124139
raise HTTPException(
125140
status_code=400, detail="Provider and credential must be provided"
126141
)
@@ -157,6 +172,9 @@ def delete_provider_credential(
157172
project_id=_current_user.project_id,
158173
)
159174
if provider_creds is None:
175+
logger.error(
176+
f"[delete_provider_credential] Provider credentials not found | organization_id: {_current_user.organization_id}, provider: {provider}, project_id: {_current_user.project_id}"
177+
)
160178
raise HTTPException(status_code=404, detail="Provider credentials not found")
161179

162180
remove_provider_credential(
@@ -188,6 +206,9 @@ def delete_all_credentials(
188206
project_id=_current_user.project_id,
189207
)
190208
if not creds:
209+
logger.error(
210+
f"[delete_all_credentials] Credentials not found | organization_id: {_current_user.organization_id}, project_id: {_current_user.project_id}"
211+
)
191212
raise HTTPException(
192213
status_code=404, detail="Credentials for organization/project not found"
193214
)

backend/app/api/routes/users.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import uuid
1+
import logging
22
from typing import Any
33

44
from fastapi import APIRouter, Depends
@@ -26,6 +26,7 @@
2626
from app.utils import generate_new_account_email, send_email
2727
from app.core.exception_handlers import HTTPException
2828

29+
logger = logging.getLogger(__name__)
2930
router = APIRouter(prefix="/users", tags=["users"])
3031

3132

@@ -49,6 +50,9 @@ def read_users(session: SessionDep, skip: int = 0, limit: int = 100) -> Any:
4950
)
5051
def create_user_endpoint(*, session: SessionDep, user_in: UserCreate) -> Any:
5152
if get_user_by_email(session=session, email=user_in.email):
53+
logger.error(
54+
f"[create_user_endpoint] Attempting to create user with existing email | email: {user_in.email}"
55+
)
5256
raise HTTPException(
5357
status_code=400,
5458
detail="The user with this email already exists in the system.",
@@ -75,6 +79,9 @@ def update_user_me(
7579
if user_in.email:
7680
existing_user = get_user_by_email(session=session, email=user_in.email)
7781
if existing_user and existing_user.id != current_user.id:
82+
logger.error(
83+
f"[update_user_me] Attempting to update user with existing email | email: {user_in.email}, user_id: {current_user.id}"
84+
)
7885
raise HTTPException(
7986
status_code=409, detail="User with this email already exists"
8087
)
@@ -83,6 +90,7 @@ def update_user_me(
8390
session.add(current_user)
8491
session.commit()
8592
session.refresh(current_user)
93+
logger.info(f"[update_user_me] User updated | user_id: {current_user.id}")
8694
return current_user
8795

8896

@@ -102,6 +110,7 @@ def update_password_me(
102110
current_user.hashed_password = get_password_hash(body.new_password)
103111
session.add(current_user)
104112
session.commit()
113+
logger.info(f"[update_password_me] Password updated | user_id: {current_user.id}")
105114
return Message(message="Password updated successfully")
106115

107116

@@ -113,11 +122,15 @@ def read_user_me(current_user: CurrentUser) -> Any:
113122
@router.delete("/me", response_model=Message)
114123
def delete_user_me(session: SessionDep, current_user: CurrentUser) -> Any:
115124
if current_user.is_superuser:
125+
logger.error(
126+
f"[delete_user_me] Attempting to delete superuser account by itself | user_id: {current_user.id}"
127+
)
116128
raise HTTPException(
117129
status_code=403, detail="Super users are not allowed to delete themselves"
118130
)
119131
session.delete(current_user)
120132
session.commit()
133+
logger.info(f"[delete_user_me] User deleted | user_id: {current_user.id}")
121134
return Message(message="User deleted successfully")
122135

123136

@@ -131,6 +144,9 @@ def register_user(session: SessionDep, user_in: UserRegister) -> Any:
131144
This endpoint allows the registration of a new user and is accessible only by a superuser.
132145
"""
133146
if get_user_by_email(session=session, email=user_in.email):
147+
logger.error(
148+
f"[register_user] Attempting to create user with existing email | email: {user_in.email}"
149+
)
134150
raise HTTPException(
135151
status_code=400,
136152
detail="The user with this email already exists in the system",
@@ -171,6 +187,7 @@ def update_user_endpoint(
171187
) -> Any:
172188
db_user = session.get(User, user_id)
173189
if not db_user:
190+
logger.error(f"[update_user_endpoint] User not found | user_id: {user_id}")
174191
raise HTTPException(
175192
status_code=404,
176193
detail="The user with this id does not exist in the system",
@@ -179,6 +196,9 @@ def update_user_endpoint(
179196
if user_in.email:
180197
existing_user = get_user_by_email(session=session, email=user_in.email)
181198
if existing_user and existing_user.id != user_id:
199+
logger.error(
200+
f"[update_user_endpoint] Attempting to update user with existing email | email: {user_in.email}, user_id: {user_id}"
201+
)
182202
raise HTTPException(
183203
status_code=409, detail="User with this email already exists"
184204
)
@@ -196,13 +216,18 @@ def delete_user(
196216
) -> Message:
197217
user = session.get(User, user_id)
198218
if not user:
219+
logger.error(f"[delete_user] User not found | user_id: {user_id}")
199220
raise HTTPException(status_code=404, detail="User not found")
200221

201222
if user == current_user:
223+
logger.error(
224+
f"[delete_user] Attempting to delete self by superuser | user_id: {current_user.id}"
225+
)
202226
raise HTTPException(
203227
status_code=403, detail="Super users are not allowed to delete themselves"
204228
)
205229

206230
session.delete(user)
207231
session.commit()
232+
logger.info(f"[delete_user] User deleted | user_id: {user.id}")
208233
return Message(message="User deleted successfully")

backend/app/core/providers.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1+
import logging
12
from typing import Dict, List, Optional
23
from enum import Enum
34
from dataclasses import dataclass
45

6+
logger = logging.getLogger(__name__)
7+
58

69
class Provider(str, Enum):
710
"""Enumeration of supported credential providers."""
@@ -46,6 +49,9 @@ def validate_provider(provider: str) -> Provider:
4649
return Provider(provider.lower())
4750
except ValueError:
4851
supported = ", ".join(p.value for p in Provider)
52+
logger.error(
53+
f"[validate_provider] Unsupported provider | provider: {provider}, supported_providers: {supported}"
54+
)
4955
raise ValueError(
5056
f"Unsupported provider: {provider}. Supported providers are: {supported}"
5157
)
@@ -67,6 +73,9 @@ def validate_provider_credentials(provider: str, credentials: Dict[str, str]) ->
6773
if missing_fields := [
6874
field for field in required_fields if field not in credentials
6975
]:
76+
logger.error(
77+
f"[validate_provider_credentials] Missing required fields | provider: {provider}, missing_fields: {', '.join(missing_fields)}"
78+
)
7079
raise ValueError(
7180
f"Missing required fields for {provider}: {', '.join(missing_fields)}"
7281
)

backend/app/core/util.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,15 @@
99
from langfuse.decorators import langfuse_context
1010
from openai import OpenAI
1111

12+
logger = logging.getLogger(__name__)
13+
1214

1315
def now():
1416
return datetime.now(timezone.utc).replace(tzinfo=None)
1517

1618

1719
def raise_from_unknown(error: Exception, status_code=500):
18-
warnings.warn(
20+
logger.warning(
1921
'Unexpected exception "{}": {}'.format(
2022
type(error).__name__,
2123
error,
@@ -31,7 +33,7 @@ def post_callback(url: HttpUrl, payload: BaseModel):
3133
try:
3234
response.raise_for_status()
3335
except RequestException as err:
34-
warnings.warn(f"Callback failure: {err}")
36+
logger.warning(f"Callback failure: {err}")
3537
errno += 1
3638

3739
return not errno
@@ -67,7 +69,7 @@ def configure_langfuse(credentials: dict) -> tuple[Langfuse, bool]:
6769

6870
return langfuse, True
6971
except Exception as e:
70-
warnings.warn(f"Failed to configure Langfuse: {str(e)}")
72+
logger.error(f"Failed to configure Langfuse: {str(e)}")
7173
return None, False
7274

7375

@@ -89,5 +91,5 @@ def configure_openai(credentials: dict) -> tuple[OpenAI, bool]:
8991
client = OpenAI(api_key=credentials["api_key"])
9092
return client, True
9193
except Exception as e:
92-
warnings.warn(f"Failed to configure OpenAI client: {str(e)}")
94+
logger.error(f"Failed to configure OpenAI client: {str(e)}")
9395
return None, False

backend/app/crud/credentials.py

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
1+
import logging
12
from typing import Optional, Dict, Any, List, Union
23
from sqlmodel import Session, select
34
from sqlalchemy.exc import IntegrityError
4-
from datetime import datetime, timezone
55

66
from app.models import Credential, CredsCreate, CredsUpdate
77
from app.core.providers import (
88
validate_provider,
99
validate_provider_credentials,
10-
get_supported_providers,
1110
)
1211
from app.core.security import encrypt_credentials, decrypt_credentials
1312
from app.core.util import now
1413
from app.core.exception_handlers import HTTPException
1514

15+
logger = logging.getLogger(__name__)
16+
1617

1718
def set_creds_for_org(
1819
*, session: Session, creds_add: CredsCreate, organization_id: int, project_id: int
@@ -21,6 +22,9 @@ def set_creds_for_org(
2122
created_credentials = []
2223

2324
if not creds_add.credential:
25+
logger.error(
26+
f"[set_creds_for_org] No credentials provided | project_id: {project_id}"
27+
)
2428
raise HTTPException(400, "No credentials provided")
2529

2630
for provider, credentials in creds_add.credential.items():
@@ -47,10 +51,16 @@ def set_creds_for_org(
4751
created_credentials.append(credential)
4852
except IntegrityError as e:
4953
session.rollback()
54+
logger.error(
55+
f"[set_creds_for_org] Integrity error while adding credentials | organization_id {organization_id}, project_id {project_id}, provider {provider}: {str(e)}",
56+
exc_info=True,
57+
)
5058
raise ValueError(
5159
f"Error while adding credentials for provider {provider}: {str(e)}"
5260
)
53-
61+
logger.info(
62+
f"[set_creds_for_org] Successfully created credentials | organization_id {organization_id}, project_id {project_id}"
63+
)
5464
return created_credentials
5565

5666

@@ -153,6 +163,9 @@ def update_creds_for_org(
153163
)
154164
creds = session.exec(statement).first()
155165
if creds is None:
166+
logger.error(
167+
f"[update_creds_for_org] Credentials not found | organization {org_id}, provider {creds_in.provider}, project_id {project_id}"
168+
)
156169
raise HTTPException(
157170
status_code=404, detail="Credentials not found for this provider"
158171
)
@@ -162,7 +175,9 @@ def update_creds_for_org(
162175
session.add(creds)
163176
session.commit()
164177
session.refresh(creds)
165-
178+
logger.info(
179+
f"[update_creds_for_org] Successfully updated credentials | organization_id {org_id}, provider {creds_in.provider}, project_id {project_id}"
180+
)
166181
return [creds]
167182

168183

@@ -186,7 +201,9 @@ def remove_provider_credential(
186201
session.add(creds)
187202
session.commit()
188203
session.refresh(creds)
189-
204+
logger.info(
205+
f"[remove_provider_credential] Successfully removed credentials for provider | organization_id {org_id}, provider {provider}, project_id {project_id}"
206+
)
190207
return creds
191208

192209

@@ -207,4 +224,7 @@ def remove_creds_for_org(
207224
session.add(cred)
208225

209226
session.commit()
227+
logger.info(
228+
f"[remove_creds_for_org] Successfully removed all the credentials | organization_id {org_id}, project_id {project_id}"
229+
)
210230
return creds

backend/app/crud/user.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
1-
import uuid
1+
import logging
22
from typing import Any
33

44
from sqlmodel import Session, select
55

66
from app.core.security import get_password_hash, verify_password
7+
78
from app.models import User, UserCreate, UserUpdate
89

10+
logger = logging.getLogger(__name__)
11+
912

1013
def create_user(*, session: Session, user_create: UserCreate) -> User:
1114
db_obj = User.model_validate(
@@ -14,6 +17,7 @@ def create_user(*, session: Session, user_create: UserCreate) -> User:
1417
session.add(db_obj)
1518
session.commit()
1619
session.refresh(db_obj)
20+
logger.info(f"[create_user] User created | user_id: {db_obj.id}")
1721
return db_obj
1822

1923

@@ -28,6 +32,9 @@ def update_user(*, session: Session, db_user: User, user_in: UserUpdate) -> Any:
2832
session.add(db_user)
2933
session.commit()
3034
session.refresh(db_user)
35+
logger.info(
36+
f"[update_user] User updated | user_id: {db_user.id}, updated_fields: {list(user_data.keys())}"
37+
)
3138
return db_user
3239

3340

backend/app/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ def get_openai_client(session: Session, org_id: int, project_id: int) -> OpenAI:
179179
)
180180

181181
if not credentials or "api_key" not in credentials:
182-
logger.warning(
182+
logger.error(
183183
f"[get_openai_client] OpenAI credentials not found. | project_id: {project_id}"
184184
)
185185
raise HTTPException(

0 commit comments

Comments
 (0)