Skip to content

Feat/logging implementation#140

Open
annikaholmqvist94 wants to merge 8 commits intomainfrom
feat/logging-implementation
Open

Feat/logging implementation#140
annikaholmqvist94 wants to merge 8 commits intomainfrom
feat/logging-implementation

Conversation

@annikaholmqvist94
Copy link
Copy Markdown
Contributor

@annikaholmqvist94 annikaholmqvist94 commented Apr 7, 2026

Modifierade filer: 8 controllers + 7 services (UserService, PetService, ClinicService, VetService, MedicalRecordService, CommentService, ActivityLogService).

Lämnade som de var (hade redan SLF4J): AttachmentService, FileStorageService, GlobalExceptionHandler. Skippad per policy: SecurityConfig (bara @Bean-wiring).

Policy som applicerades:

  • Controllers: INFO vid endpoint-entry med metod + key id
  • Services: DEBUG för läsningar, INFO för lyckade mutationer, WARN precis före business-rule throws
  • {}-placeholders genomgående, inga lösenord/tokens/full bodies loggas

Summary by CodeRabbit

  • Chores
    • Enhanced system logging across controllers and services for improved operational visibility and debugging capabilities.

Note: This release contains no changes visible to end-users. All modifications are internal infrastructure improvements.

- Introduced `SLF4J` logging for key actions in `VetController` (e.g., endpoints: `create`, `getAll`, `getById`) and `VetService` (e.g., methods: `createVet`, `getAllVets`, `getVetById`).
- Enhanced traceability and debugging capabilities by logging request details and actions.
- Introduced `SLF4J` logging in `PetController` and `PetService` for key actions (create, read, update, delete).
- Improved traceability and debugging by logging request details and method activities.
- Introduced `SLF4J` logging in `UserController` and `UserService` for key actions (create, read, update, delete).
- Enhanced traceability and debugging by logging request details and method activities.
- Introduced `SLF4J` logging in `ClinicController` and `ClinicService` for key actions (create, read, update, delete).
- Enhanced traceability and debugging by logging request details and method activities.
- Introduced `SLF4J` logging in `MedicalRecordController` and `MedicalRecordService` for key actions (create, read, update, delete).
- Enhanced traceability and debugging by logging request details and method activities.
- Introduced `SLF4J` logging in `CommentController` and `CommentService` for key actions (create, read, update, delete, count).
- Enhanced traceability and debugging by logging request details and method activities.
- Introduced `SLF4J` logging in `ActivityLogController` and `ActivityLogService` for key actions (create, read).
- Enhanced traceability and debugging by logging request details and method activities.
- Introduced `SLF4J` logging in `AttachmentController` for key actions (create, read, delete).
- Enhanced traceability and debugging by logging request details for API endpoints.

Closes #94
@annikaholmqvist94
Copy link
Copy Markdown
Contributor Author

Closes #94

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 7, 2026

📝 Walkthrough

Walkthrough

This PR introduces SLF4J logging instrumentation across the application by adding static logger instances and log statements to seven controllers and seven service classes. Each endpoint and service method now emits log entries at appropriate levels (info, debug, warn) with relevant request parameters and operation details.

Changes

Cohort / File(s) Summary
Controllers - Activity & Attachment
src/main/java/org/example/vet1177/controller/ActivityLogController.java, src/main/java/org/example/vet1177/controller/AttachmentController.java
Added static logger and info-level logging to endpoint handlers. ActivityLogController logs the GET recordId endpoint; AttachmentController logs all four endpoints (upload, list, download, delete) with relevant path variables.
Controllers - Clinic & Comment
src/main/java/org/example/vet1177/controller/ClinicController.java, src/main/java/org/example/vet1177/controller/CommentController.java
Added static logger with info-level logs for all CRUD endpoints. ClinicController logs all five endpoints including ids; CommentController logs five endpoints with recordId and commentId tracking.
Controllers - Medical Record, Pet, User, Vet
src/main/java/org/example/vet1177/controller/MedicalRecordController.java, src/main/java/org/example/vet1177/controller/PetController.java, src/main/java/org/example/vet1177/controller/UserController.java, src/main/java/org/example/vet1177/controller/VetController.java
Added static logger with info-level logs across multiple endpoints. MedicalRecordController covers eleven endpoints; PetController logs create; UserController covers five endpoints; VetController logs three endpoints.
Services - Activity Log & Clinic
src/main/java/org/example/vet1177/services/ActivityLogService.java, src/main/java/org/example/vet1177/services/ClinicService.java
Added static logger with mixed-level logging. ActivityLogService logs warnings on null input and info after persist; ClinicService logs info on create/update/delete and debug on read operations.
Services - Comment & Medical Record
src/main/java/org/example/vet1177/services/CommentService.java, src/main/java/org/example/vet1177/services/MedicalRecordService.java
Added static logger with info-level logs for mutations and debug-level for reads. CommentService logs across five methods; MedicalRecordService logs across eleven methods with relevant UUIDs.
Services - Pet, User, Vet
src/main/java/org/example/vet1177/services/PetService.java, src/main/java/org/example/vet1177/services/UserService.java, src/main/java/org/example/vet1177/services/VetService.java
Added static logger with tiered logging strategy. PetService logs create/update/delete at info and reads at debug; UserService logs warnings on duplicate email and data integrity violations; VetService logs create at info and reads at debug.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

infrastruktur

Suggested reviewers

  • lindaeskilsson
  • TatjanaTrajkovic
  • johanbriger

Poem

🐰 Hark! The logs now flow like carrots so bright,
Each endpoint whispering through the night,
Services chat with debug and with info's delight,
The SLF4J hops make the code truly light! 🥕✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 58.75% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Feat/logging implementation' is directly related to the main changeset, which adds SLF4J logging across 8 controllers and 7 services throughout the codebase.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/logging-implementation

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (4)
src/main/java/org/example/vet1177/services/VetService.java (1)

40-46: Consider adding WARN logs before business-rule exceptions.

Per the PR's stated logging policy ("WARN precis före business-rule throws"), these BusinessRuleException throws should be preceded by warn-level logs for consistency with the rest of the codebase.

📝 Suggested addition
                 if (vetRepository.existsByLicenseId(request.licenseId())) {
+                    log.warn("License ID already exists: {}", request.licenseId());
                     throw new BusinessRuleException("Licens-ID " + request.licenseId() + " används redan");
                 }

                 if(vetRepository.existsById(request.userId())){
+                    log.warn("User already registered as vet userId={}", request.userId());
                     throw new BusinessRuleException("Användaren är redan registrerad som veterinär");
                 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/org/example/vet1177/services/VetService.java` around lines 40 -
46, Add WARN-level logging immediately before each BusinessRuleException throw
in the VetService registration flow: log a warning using the same logger used by
this class (e.g., logger.warn(...)) right before the check that throws for
vetRepository.existsByLicenseId(request.licenseId()) and before the check that
throws for vetRepository.existsById(request.userId()); include the conflicting
identifier (request.licenseId() or request.userId()) and a short message
matching the exception text so logs and exceptions correlate.
src/main/java/org/example/vet1177/services/ActivityLogService.java (2)

42-42: Variable naming creates potential confusion.

The local variable log (an ActivityLog entity) shadows what would be the typical logger variable name. While this works because the class uses LOG instead of log, it could cause confusion for future maintainers. Consider renaming the local variable to activityLog for clarity.

Suggested change
-        ActivityLog log = new ActivityLog(action, description, user, record);
-        repository.save(log);
+        ActivityLog activityLog = new ActivityLog(action, description, user, record);
+        repository.save(activityLog);

And on line 62:

-                .filter(log -> canView(currentUser, log))
+                .filter(entry -> canView(currentUser, entry))

Also applies to: 62-62

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/org/example/vet1177/services/ActivityLogService.java` at line
42, Rename the local variable named "log" in ActivityLogService to avoid
confusion with logger; change occurrences where an ActivityLog is
constructed/used (e.g., the constructor call ActivityLog log = new
ActivityLog(action, description, user, record) and the other usage at the second
occurrence) to a clearer name like "activityLog" and update all subsequent
references in the same method (such as any save or return calls) to that new
identifier; keep the class-level logger (LOG) unchanged.

21-22: Logger naming inconsistency with other files.

This file uses LOG (uppercase) while all other files in this PR use log (lowercase). Consider using consistent naming across the codebase.

Suggested change for consistency
-    private static final Logger LOG = LoggerFactory.getLogger(ActivityLogService.class);
+    private static final Logger log = LoggerFactory.getLogger(ActivityLogService.class);

Note: If you rename to log, you'll need to also rename the ActivityLog log variable on line 42 to avoid shadowing (e.g., ActivityLog activityLog).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/org/example/vet1177/services/ActivityLogService.java` around
lines 21 - 22, Rename the logger constant in ActivityLogService from LOG to log
to match project convention (change Logger LOG =
LoggerFactory.getLogger(ActivityLogService.class) to Logger log = ...), and also
rename the method-local or field variable of type ActivityLog currently named
log to avoid shadowing (e.g., rename the ActivityLog variable to activityLog) so
there is no name conflict between the logger and the ActivityLog instance;
update all references to these symbols (ActivityLogService.log and ActivityLog
activityLog) accordingly.
src/main/java/org/example/vet1177/services/MedicalRecordService.java (1)

143-145: Consider adding WARN logs before throwing BusinessRuleException.

Per the PR's stated logging policy ("WARN precis före business-rule throws"), the BusinessRuleException throws at lines 144, 169-171, 174-176, 204, and 235 lack preceding WARN logs. This is a minor inconsistency with the stated policy.

Example for line 143-145
         if (record.getStatus().isFinal()) {
+            log.warn("Attempt to update closed record id={}", id);
             throw new BusinessRuleException("Stängda ärenden kan inte uppdateras");
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/org/example/vet1177/services/MedicalRecordService.java` around
lines 143 - 145, In MedicalRecordService, add a WARN log immediately before each
BusinessRuleException throw (including the record.getStatus().isFinal() check
and the other throw sites referenced) so the code follows the "WARN before
business-rule throws" policy; use the class logger (e.g. logger.warn or
log.warn) to emit a concise contextual message that includes the record
identifier and status/action being prevented, then throw the
BusinessRuleException as before (ensure the WARN is placed directly above the
throw in each throw site).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/main/java/org/example/vet1177/services/UserService.java`:
- Line 58: Don't log raw email addresses in UserService; in createUser,
duplicate-email warnings, and getByEmail replace direct logging of
request.getEmail()/email with a privacy-safe value (either a masked form or a
deterministic hash) or, after successful creation, log the created user's
identifier (user.getId()). Introduce/use a small utility (e.g., maskEmail or
hashEmail) and call it where log.info("Creating user..."), the duplicate-email
log (log.warn...), and in getByEmail so logs contain no raw PII.

---

Nitpick comments:
In `@src/main/java/org/example/vet1177/services/ActivityLogService.java`:
- Line 42: Rename the local variable named "log" in ActivityLogService to avoid
confusion with logger; change occurrences where an ActivityLog is
constructed/used (e.g., the constructor call ActivityLog log = new
ActivityLog(action, description, user, record) and the other usage at the second
occurrence) to a clearer name like "activityLog" and update all subsequent
references in the same method (such as any save or return calls) to that new
identifier; keep the class-level logger (LOG) unchanged.
- Around line 21-22: Rename the logger constant in ActivityLogService from LOG
to log to match project convention (change Logger LOG =
LoggerFactory.getLogger(ActivityLogService.class) to Logger log = ...), and also
rename the method-local or field variable of type ActivityLog currently named
log to avoid shadowing (e.g., rename the ActivityLog variable to activityLog) so
there is no name conflict between the logger and the ActivityLog instance;
update all references to these symbols (ActivityLogService.log and ActivityLog
activityLog) accordingly.

In `@src/main/java/org/example/vet1177/services/MedicalRecordService.java`:
- Around line 143-145: In MedicalRecordService, add a WARN log immediately
before each BusinessRuleException throw (including the
record.getStatus().isFinal() check and the other throw sites referenced) so the
code follows the "WARN before business-rule throws" policy; use the class logger
(e.g. logger.warn or log.warn) to emit a concise contextual message that
includes the record identifier and status/action being prevented, then throw the
BusinessRuleException as before (ensure the WARN is placed directly above the
throw in each throw site).

In `@src/main/java/org/example/vet1177/services/VetService.java`:
- Around line 40-46: Add WARN-level logging immediately before each
BusinessRuleException throw in the VetService registration flow: log a warning
using the same logger used by this class (e.g., logger.warn(...)) right before
the check that throws for vetRepository.existsByLicenseId(request.licenseId())
and before the check that throws for vetRepository.existsById(request.userId());
include the conflicting identifier (request.licenseId() or request.userId()) and
a short message matching the exception text so logs and exceptions correlate.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6c3fac57-16be-4d60-b348-eb56f45e41f5

📥 Commits

Reviewing files that changed from the base of the PR and between 47c17c6 and 3464169.

📒 Files selected for processing (15)
  • src/main/java/org/example/vet1177/controller/ActivityLogController.java
  • src/main/java/org/example/vet1177/controller/AttachmentController.java
  • src/main/java/org/example/vet1177/controller/ClinicController.java
  • src/main/java/org/example/vet1177/controller/CommentController.java
  • src/main/java/org/example/vet1177/controller/MedicalRecordController.java
  • src/main/java/org/example/vet1177/controller/PetController.java
  • src/main/java/org/example/vet1177/controller/UserController.java
  • src/main/java/org/example/vet1177/controller/VetController.java
  • src/main/java/org/example/vet1177/services/ActivityLogService.java
  • src/main/java/org/example/vet1177/services/ClinicService.java
  • src/main/java/org/example/vet1177/services/CommentService.java
  • src/main/java/org/example/vet1177/services/MedicalRecordService.java
  • src/main/java/org/example/vet1177/services/PetService.java
  • src/main/java/org/example/vet1177/services/UserService.java
  • src/main/java/org/example/vet1177/services/VetService.java

passwordHash,
request.getRole());
applyClinicRules(user, request.getClinicId());
log.info("Creating user with email={}", request.getEmail());
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Consider not logging email addresses for privacy compliance.

Email addresses are PII (Personally Identifiable Information). Logging them may create GDPR/CCPA compliance concerns, as logs often have different retention policies and access controls than primary data stores.

Consider logging user IDs instead after the user is created, or using a masked/hashed representation.

Suggested changes

For line 58 (createUser):

-        log.info("Creating user with email={}", request.getEmail());
+        log.info("Creating user");

For line 62 (duplicate email warning):

-            log.warn("Duplicate email on create: {}", request.getEmail());
+            log.warn("Duplicate email on create");

For line 69 (getByEmail):

-        log.debug("Fetching user by email={}", email);
+        log.debug("Fetching user by email");

Also applies to: 62-62, 69-69

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/org/example/vet1177/services/UserService.java` at line 58,
Don't log raw email addresses in UserService; in createUser, duplicate-email
warnings, and getByEmail replace direct logging of request.getEmail()/email with
a privacy-safe value (either a masked form or a deterministic hash) or, after
successful creation, log the created user's identifier (user.getId()).
Introduce/use a small utility (e.g., maskEmail or hashEmail) and call it where
log.info("Creating user..."), the duplicate-email log (log.warn...), and in
getByEmail so logs contain no raw PII.

@lindaeskilsson
Copy link
Copy Markdown
Contributor

Ser bra ut! Tror du vi ska vänta med att logga userId tills security är på plats, så vi slipper röra samma kod två gånger?

Copy link
Copy Markdown
Contributor

@TatjanaTrajkovic TatjanaTrajkovic left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good! Main suggestion is to standardize authentication approach and avoid logging sensitive data like emails.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants