Skip to content

fix(logging): use logger instead of console in stack modules#3442

Merged
PierreBrisorgueil merged 5 commits intomasterfrom
fix/use-logger-instead-of-console-3434
Apr 9, 2026
Merged

fix(logging): use logger instead of console in stack modules#3442
PierreBrisorgueil merged 5 commits intomasterfrom
fix/use-logger-instead-of-console-3434

Conversation

@PierreBrisorgueil
Copy link
Copy Markdown
Contributor

@PierreBrisorgueil PierreBrisorgueil commented Apr 9, 2026

Summary

  • Replace console.error/console.log/console.warn/console.info with the Winston-based logger from lib/services/logger.js across all production stack modules
  • Ensures structured logging, Sentry error capture, and consistent log formatting
  • Updated unit tests to mock logger and verify logger calls instead of console spies

Scope

Changed (10 production files):

  • server.js, lib/app.js, lib/services/mongoose.js, lib/services/migrations.js, lib/services/seed.js, lib/services/express.js, lib/services/sentry.js, lib/helpers/mailer/index.js, modules/billing/controllers/billing.webhook.controller.js, modules/audit/audit.init.js

Updated tests (4 files):

  • lib/services/tests/sentry.unit.tests.js, lib/helpers/mailer/tests/mailer.unit.tests.js, modules/billing/tests/billing.controller.unit.tests.js, modules/core/tests/core.integration.tests.js

Intentionally excluded (bootstrap/config layer):

  • config/index.js, lib/helpers/config.js — loaded before logger is initialized (circular dependency)
  • lib/services/logger.js — is the logger itself, must use console
  • scripts/seed.js — CLI script, console is appropriate
  • Test files — console.log(err) in catch blocks is acceptable for test debugging

Test plan

  • npm run lint passes
  • npm run test:coverage — 64 suites, 756 tests, all green
  • No coverage threshold regressions

Closes #3434

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Corrected NODE_ENV environment variable label typo.
  • Chores

    • Centralized application logging through a dedicated logger service for improved consistency.
    • Enhanced credential masking for sensitive database connection information in logs.
    • Improved test suite reliability with enhanced database cleanup procedures.

Auth integration tests used hardcoded emails without cleaning the
database before each run. On shared MongoDB instances (e.g. ARC
self-hosted runners), stale data from previous CI runs caused
cascading test failures.

Add pre-signup cleanup in all beforeAll/beforeEach hooks across
the four auth integration test files to purge any leftover users
by email before attempting signup.

Closes #3437
Replace console.error/log/warn/info with the Winston-based logger from
lib/services/logger.js across all production stack modules. This ensures
structured logging, Sentry capture, and consistent log formatting.

Files excluded from this change:
- config/index.js and lib/helpers/config.js (loaded before logger init)
- lib/services/logger.js (is the logger itself)
- scripts/seed.js (CLI script)
- Test files (except where assertions needed updating)

Closes #3434
Copilot AI review requested due to automatic review settings April 9, 2026 06:01
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 9, 2026

Warning

Rate limit exceeded

@PierreBrisorgueil has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 8 minutes and 29 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 8 minutes and 29 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 477d180f-f159-412d-8e4d-bd680342b6f5

📥 Commits

Reviewing files that changed from the base of the PR and between 15aa42a and b798ce2.

📒 Files selected for processing (2)
  • lib/app.js
  • lib/services/migrations.js

Walkthrough

The changes systematically replace all console.* logging calls with a shared logger service throughout the application (core services, helpers, modules, and server bootstrap). Additionally, pre-test database cleanup steps are added to auth integration tests to remove stale users by email before test execution, and test mocks are updated to verify logger calls instead of console output.

Changes

Cohort / File(s) Summary
Core Service Logging Migration
lib/app.js, lib/services/express.js, lib/services/mongoose.js, lib/services/migrations.js, lib/services/seed.js, lib/services/sentry.js
Replaced all console.* calls with logger.error(), logger.warn(), or logger.info(). Fixed NODE_ENV typo ('develoment''development'), sanitized database URI before logging by masking credentials, and updated error logging to pass full error objects instead of just messages.
Helper Logging Migration
lib/helpers/mailer/index.js
Replaced console.error() with logger.error() in mail send error handling.
Module Logging Migration
modules/billing/controllers/billing.webhook.controller.js, modules/audit/audit.init.js
Replaced console.error() and console.log() with logger.error() and logger.info() for Stripe webhook errors and audit initialization status.
Test Logger Mocks
lib/helpers/mailer/tests/mailer.unit.tests.js, lib/services/tests/sentry.unit.tests.js, modules/billing/tests/billing.controller.unit.tests.js, modules/core/tests/core.integration.tests.js
Added Jest module mocks for logger service (error, warn, info, debug functions) and updated assertions to verify logger calls instead of console calls.
Auth Integration Test Database Cleanup
modules/auth/tests/auth.abilities.integration.tests.js, modules/auth/tests/auth.authorization.integration.tests.js, modules/auth/tests/auth.integration.tests.js, modules/auth/tests/auth.signup.organization.integration.tests.js
Added pre-test cleanup using UserService.getBrut() and UserService.remove() to purge stale users by email before test execution, with errors suppressed to prevent cleanup failures from blocking tests. Introduced a local purgeUser() helper in signup tests.
Server Bootstrap
server.js
Replaced console.log() and console.info() with logger.error() and logger.info() for startup failures and graceful shutdown signal handlers.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

Suggested labels

Fix

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Out of Scope Changes check ❓ Inconclusive The PR includes intentional cleanup of stale test users in auth integration tests, which addresses CI flakiness on shared databases—a closely related but technically out-of-scope concern from the main logger migration. Clarify whether test cleanup changes (auth integration tests) belong in this logging PR or should be separated into a distinct pull request for better scope isolation.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: replacing console logging with logger service across stack modules, which is the primary objective of the PR.
Description check ✅ Passed The description covers all template sections including summary, scope, validation, guardrails checks, and notes for reviewers. All critical information is present and complete.
Linked Issues check ✅ Passed The PR fully implements the objectives from issue #3434: console.error/log/warn/info replaced with logger across production modules, structured logging enabled, and test mocks added.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/use-logger-instead-of-console-3434

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.

@codecov
Copy link
Copy Markdown

codecov bot commented Apr 9, 2026

Codecov Report

❌ Patch coverage is 45.45455% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.54%. Comparing base (b4e2da9) to head (b798ce2).
⚠️ Report is 4 commits behind head on master.

Files with missing lines Patch % Lines
lib/services/seed.js 33.33% 4 Missing ⚠️
lib/services/migrations.js 57.14% 3 Missing ⚠️
lib/services/express.js 33.33% 2 Missing ⚠️
lib/services/mongoose.js 50.00% 2 Missing ⚠️
lib/services/sentry.js 0.00% 1 Missing ⚠️

❌ Your patch status has failed because the patch coverage (45.45%) is below the target coverage (80.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3442      +/-   ##
==========================================
+ Coverage   85.51%   85.54%   +0.02%     
==========================================
  Files         113      113              
  Lines        2879     2878       -1     
  Branches      795      795              
==========================================
  Hits         2462     2462              
+ Misses        331      330       -1     
  Partials       86       86              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@PierreBrisorgueil
Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 9, 2026

✅ Actions performed

Full review triggered.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Replaces direct console.* usage with the centralized Winston logger across core runtime/services to standardize logging behavior, and updates affected tests to assert against logger calls.

Changes:

  • Swap console.log/info/warn/error for logger.* in server bootstrap and stack services (app init, mongoose, migrations, seed, express error paths, mailer, sentry, audit, billing webhook).
  • Update unit/integration tests to mock/spy on logger instead of console.
  • Add stale-test-data cleanup in multiple auth integration suites to reduce flakiness on shared databases.

Reviewed changes

Copilot reviewed 18 out of 18 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
server.js Uses logger for startup/shutdown logging.
lib/app.js Uses logger for startup configuration/readiness logging and shutdown logs.
lib/services/mongoose.js Logs connect/disconnect and connection failures via logger.
lib/services/migrations.js Logs migration progress/errors via logger.
lib/services/seed.js Logs seed progress/errors via logger.
lib/services/express.js Logs route-loading and error middleware output via logger.
lib/services/sentry.js Logs Sentry init failures via logger.
lib/helpers/mailer/index.js Logs mail send failures via logger.
modules/billing/controllers/billing.webhook.controller.js Logs webhook handler failures via logger.
modules/audit/audit.init.js Logs module enablement via logger.
lib/services/tests/sentry.unit.tests.js Mocks logger for Sentry service tests.
lib/helpers/mailer/tests/mailer.unit.tests.js Mocks logger for mailer tests.
modules/billing/tests/billing.controller.unit.tests.js Mocks logger and asserts logger.error calls.
modules/core/tests/core.integration.tests.js Spies on logger.info to verify seed logging.
modules/auth/tests/auth.signup.organization.integration.tests.js Adds helper to purge stale users before signup org tests.
modules/auth/tests/auth.integration.tests.js Adds stale-user cleanup in multiple auth flows.
modules/auth/tests/auth.authorization.integration.tests.js Adds stale-user cleanup before authz tests.
modules/auth/tests/auth.abilities.integration.tests.js Adds stale-user cleanup before abilities tests.

… secrets

- Log full Error objects instead of just .message (server.js, mailer, sentry)
- Remove JSON.stringify wrapping on error messages (server.js)
- Fix 'develoment' typo → 'development' (lib/app.js)
- Redact DB URI credentials before logging (lib/app.js)
- Redact seed passwords from log output (lib/services/seed.js)
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: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@lib/app.js`:
- Around line 174-177: The success log is emitted unconditionally before error
handling; modify the server close callback so that
logger.info(chalk.yellow('Server closed')) is only called when there is no
error: keep the existing error branch (logger.error(...), process.exitCode = 1)
and move the success log into the else path (or after a conditional check of err
=== null) to avoid logging success when an error occurred; update the close
callback where logger and process.exitCode are used.
- Line 116: The readiness-check warning currently logs only err.message via
logger.warn(chalk.yellow(...)) which loses stack and structured fields; update
the readiness-check logging in lib/app.js to pass the full error object (or
err.stack) to logger.warn alongside the formatted message so the stack and
metadata are preserved — locate the logger.warn(...) call in the
readiness-check/initialization code and change it to include the err as an
additional argument (or include err.stack in the message) so diagnostics retain
full error details.

In `@lib/services/migrations.js`:
- Around line 151-152: The migration failure log currently only emits
err.message which omits stack/context; update the error logging in
lib/services/migrations.js (the logger calls around Migration failed and
err.message) to log the full Error object in the same entry — e.g., pass the
Error object as an additional argument or include it in the metadata so the
logger records stack and context (replace the separate
logger.error(chalk.red(err.message)) with a single logger.error invocation that
includes the Error object).

In `@lib/services/mongoose.js`:
- Around line 47-48: Combine the two separate logger.error calls into a single
call so the context message and error object are logged together; specifically
update the error handling in the MongoDB connection code (where logger and chalk
are used, e.g., the connection failure block in lib/services/mongoose.js) to
call logger.error with the combined message and the err object (preserve
chalk.red formatting on the message) so the log entry contains both the
descriptive text and the full error/stack trace.

In `@server.js`:
- Around line 12-13: The logger.error call is currently passing the error
message and the error object separately (logger.error(e.message, e)), causing
redundant output; update the call to pass a single contextualized argument such
as a prefixed error object or a single string with the error (e.g.,
logger.error("Server failed:", e) or logger.error(e) ), so replace the current
logger.error(e.message, e) usage in server.js with a single, non-redundant
logger.error invocation that includes context and the error object (refer to
logger.error and the caught error variable e).
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9039c906-c8df-4082-9208-7db37f8ba83b

📥 Commits

Reviewing files that changed from the base of the PR and between b4e2da9 and 15aa42a.

📒 Files selected for processing (18)
  • lib/app.js
  • lib/helpers/mailer/index.js
  • lib/helpers/mailer/tests/mailer.unit.tests.js
  • lib/services/express.js
  • lib/services/migrations.js
  • lib/services/mongoose.js
  • lib/services/seed.js
  • lib/services/sentry.js
  • lib/services/tests/sentry.unit.tests.js
  • modules/audit/audit.init.js
  • modules/auth/tests/auth.abilities.integration.tests.js
  • modules/auth/tests/auth.authorization.integration.tests.js
  • modules/auth/tests/auth.integration.tests.js
  • modules/auth/tests/auth.signup.organization.integration.tests.js
  • modules/billing/controllers/billing.webhook.controller.js
  • modules/billing/tests/billing.controller.unit.tests.js
  • modules/core/tests/core.integration.tests.js
  • server.js

… close log

- Include error object in readiness-check warn (lib/app.js)
- Move success log after error check in server close callback (lib/app.js)
- Log full error object for migration failures (lib/services/migrations.js)
@PierreBrisorgueil PierreBrisorgueil merged commit b7388c3 into master Apr 9, 2026
4 of 5 checks passed
@PierreBrisorgueil PierreBrisorgueil deleted the fix/use-logger-instead-of-console-3434 branch April 9, 2026 06:39
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.

Use logger instead of console.error in stack modules

2 participants