Feature/logging app config#11
Conversation
…e funções de papel
…ss the application - Updated logger messages in authentication, authorization, role, transaction, user, and generic controller modules to use single quotes. - Adjusted string formatting in various logging statements for improved readability. - Ensured consistency in exception messages and logging throughout the application.
…definir postgres_*
There was a problem hiding this comment.
Pull request overview
This PR aims to improve observability across the FastAPI app by adding structured logging to core routers/controllers, centralizing logging configuration, and modernizing CI/environment configuration.
Changes:
- Introduces a centralized logging setup (
app/utils/logging.py) and adds log statements across multiple API modules and controllers. - Updates CI to use
uvinstead of Poetry and adjusts environment variables for test runs. - Cleans up environment configuration samples and tweaks local Docker Compose configuration.
Reviewed changes
Copilot reviewed 24 out of 25 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/conftest.py | Attempts to raise logging level during tests via env vars. |
| seeds/seed_transactions.py | Refactors seed data quoting; still seeds operation codes. |
| seeds/seed_super_user.py | Minor string quoting change. |
| pyproject.toml | Updates project metadata and dependencies (incl. FastAPI version bump, adds pyjwt). |
| compose.yml | Hardcodes Postgres container credentials and updates healthcheck accordingly. |
| app/utils/settings.py | Adds logging-related settings and removes unused setting. |
| app/utils/logging.py | Adds centralized logging configuration utilities. |
| app/utils/generic_controller.py | Adds logging around CRUD operations in the generic controller. |
| app/utils/exceptions.py | Fixes malformed module docstring. |
| app/startup.py | Calls logging setup during app import and normalizes quoting. |
| app/models/user.py | Removes ProcessedText relationship/type-check import. |
| app/api/user/router.py | Adds logging for user CRUD endpoints and access-related actions. |
| app/api/user/controller.py | Adds logging around user lookups and password hashing. |
| app/api/transaction/router.py | Adds logging for transaction CRUD endpoints. |
| app/api/transaction/enum_operation_code.py | Removes OP_2000001 enum constant. |
| app/api/role/router.py | Adds logging for role CRUD endpoints. |
| app/api/authorization/router.py | Adds logging for authorization CRUD endpoints. |
| app/api/authorization/middleware.py | Adds request timing logging to middleware. |
| app/api/authorization/controller.py | Adds logging for access validation and authorization lookup counts. |
| app/api/authentication/router.py | Adds logging around login attempts/failures. |
| app/api/authentication/controller.py | Adds logging for authentication/token validation flows. |
| app/api/assignment/router.py | Adds logging for assignment CRUD endpoints. |
| .github/workflows/ci.yml | Switches CI to uv, updates checkout action, and sets env vars. |
| .env-prod.semple | Removes redundant Postgres vars, keeping DB_URL and security/swagger vars. |
| """Application startup and configuration.""" | ||
| from fastapi import FastAPI | ||
| from fastapi.middleware.cors import CORSMiddleware | ||
| from utils.logging import setup_logging |
There was a problem hiding this comment.
setup_logging is imported from utils.logging, but there is no top-level utils/ package in the repo (only app/utils). This will raise ModuleNotFoundError when importing app.startup. Import it from app.utils.logging (or otherwise make the package layout consistent).
| from utils.logging import setup_logging | |
| from app.utils.logging import setup_logging |
| from sqlalchemy import String, and_, select | ||
| from sqlalchemy.exc import IntegrityError | ||
| from sqlalchemy.orm import Session | ||
| from utils.logging import get_logger |
There was a problem hiding this comment.
This imports get_logger from utils.logging, but the codebase uses app.utils.* imports and there is no top-level utils package. This will break at import time; switch to from app.utils.logging import get_logger (or align the package structure consistently).
| from utils.logging import get_logger | |
| from app.utils.logging import get_logger |
| import logging.handlers | ||
| from pathlib import Path | ||
|
|
||
| from utils.settings import get_settings |
There was a problem hiding this comment.
This module imports get_settings from utils.settings, but the settings live under app/utils/settings.py and there is no top-level utils package. As written, importing app.utils.logging will fail with ModuleNotFoundError. Update the import to app.utils.settings (and keep imports consistent across the project).
| from utils.settings import get_settings | |
| from app.utils.settings import get_settings |
| settings = get_settings() | ||
|
|
There was a problem hiding this comment.
settings = get_settings() is assigned at import time but never used, and setup_logging() repeatedly calls get_settings() instead. Either remove the unused settings variable or use it consistently to avoid extra lookups and to keep module import side-effects minimal.
| # TODO: Desligar logs durante os testes, ou configurar para um nível mais alto | ||
| os.environ.setdefault("LOG_LEVEL", "CRITICAL") | ||
| os.environ.setdefault("LOG_CONSOLE_LEVEL", "CRITICAL") |
There was a problem hiding this comment.
These os.environ.setdefault(...) calls happen after from app.startup import app (line 16). Since app.startup now calls setup_logging() at import time, logging will already be configured before these env vars are applied, so this won’t actually silence logs in tests. Move the env configuration above the app.startup import (or configure logging via pytest/logging config).
| 'operation_code': EnumOperationCode.OP_2000001.value, | ||
| 'name': 'Data Processing - Execute', | ||
| 'description': 'Perform data processing with AI', | ||
| 'audit_user_ip': '0.0.0.0', | ||
| 'audit_user_login': 'system', | ||
| }, |
There was a problem hiding this comment.
EnumOperationCode.OP_2000001 is referenced here, but OP_2000001 was removed from EnumOperationCode in this PR. Seeding will crash with AttributeError. Either re-add the enum value or remove/update this seed entry to match the enum.
| logger.warning( | ||
| f'Object {self.model.__name__} with ID {obj_id} not found.' | ||
| ) | ||
| raise ObjectNotFoundException(self.model.__name__, str(obj_id)) |
There was a problem hiding this comment.
The newly added log messages use f-strings (e.g., f'Object ... {obj_id} ...'). Prefer logger parameterization (logger.info('...', arg)) to avoid eager string formatting when the log level is disabled, especially in a generic controller used across the app.
| POSTGRES_USER: fastapi_user | ||
| POSTGRES_PASSWORD: fastapi_password | ||
| POSTGRES_DB: fastapi | ||
| volumes: | ||
| - postgres_data:/var/lib/postgresql/data | ||
| ports: | ||
| - "5433:5432" | ||
| healthcheck: | ||
| test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"] | ||
| test: ["CMD-SHELL", "pg_isready -U fastapi_user -d fastapi"] |
There was a problem hiding this comment.
Postgres credentials are now hardcoded in compose.yml. This reduces flexibility and can lead to accidental reuse of weak credentials across environments. Prefer ${POSTGRES_USER:-fastapi_user}-style defaults (and keep the healthcheck in sync) so users can override via .env without editing the compose file.
This pull request introduces comprehensive logging improvements across the authentication, authorization, assignment, and role API modules, enhancing observability and traceability of user actions and system events. Additionally, it updates the CI workflow to use the latest tools and simplifies environment variable management. The most important changes are grouped below:
Logging Enhancements Across API Modules:
assignment,authorization,authentication, androlerouters and controllers, including creation, update, deletion, fetching, and listing of resources, as well as authentication and access validation. This includes logging both successful operations and warnings for failures or unauthorized actions. [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25]CI Workflow Modernization:
.github/workflows/ci.ymlto useuvfor dependency management and testing, replacedactions/checkout@v3withv4, removed Poetry setup, and ensured environment variables are set for test runs.Environment Variable Cleanup:
.env-prod.semple, keeping only theDB_URLfor clarity and consistency.These changes collectively improve system reliability, make debugging easier, and modernize the development workflow.