Skip to content

Replace console.log with structured logging using Winston or Pino #161

Closed

Description

@Josie123-Dev

What

Replace all console.log and console.error calls in the backend with structured logging using Pino (or Winston). Add log levels, JSON output format, request context (request ID, user ID), and correlation IDs for tracing requests across services.

Why

The backend currently uses console.log for logging (visible in main.ts and likely scattered across services). For a health credential platform in production, this is insufficient:

  • No log levels (can't filter noise from critical errors)
  • No structured format (can't query logs in CloudWatch/Datadog)
  • No request correlation (can't trace a single request through multiple services)
  • No sensitive data filtering (health data could leak into logs)

SECURITY.md mentions Sentry and Datadog integration — structured logging is the prerequisite for both.

Scope

In scope:

  • Install nestjs-pino (or nest-winston) and configure as the NestJS logger
  • Replace all console.log/console.error calls with proper logger methods
  • Add request logging middleware (method, path, status, duration, request ID)
  • Add log levels: debug, info, warn, error
  • JSON format in production, pretty-print in development
  • Add LOG_LEVEL env var to .env.example

Out of scope:

  • Shipping logs to external services (Datadog, CloudWatch)
  • Log rotation configuration
  • Audit logging (already exists in backend/src/audit/)
  • Frontend logging

Acceptance Criteria

  • nestjs-pino (or nest-winston) is installed and configured
  • All console.log and console.error calls in backend/src/ are replaced
  • HTTP requests are logged with: method, path, status code, duration, request ID
  • Log output is JSON in production, pretty-printed in development
  • LOG_LEVEL env var controls minimum log level
  • Sensitive fields (passwords, tokens, health data) are redacted from logs
  • npm run start:dev shows colored, readable logs
  • npm run start:prod outputs JSON logs

Technical Context

  • Main bootstrap: backend/src/main.ts — replace Logger usage
  • nestjs-pino is the most popular NestJS logging integration: https://github.com/iamolegga/nestjs-pino
  • Request context: use pino-http middleware for automatic request logging
  • Correlation IDs: use nestjs-pino's req.id or X-Request-Id header
  • Redaction: use pino's redact option for sensitive fields

Activity

  1. added
    backendBackend related issues
    observabilityLogging, monitoring, tracing
    Maybe RewardedIssue may be eligible for a GrantFox reward
    GrantFox OSSIssue tracked in GrantFox OSS
    and removed on Aug 23, 2026
  2. Wilfred007 commented on Aug 23, 2026

    @Wilfred007
    Contributor

    Hi! I’d like to work on this structured logging improvement. I can migrate the backend from console.log/console.error to a production-ready Pino-based logging system while keeping observability and security in focus.

    My approach would include:

    Configuring nestjs-pino as the NestJS logger with debug, info, warn, and error levels.
    Replacing scattered console calls with structured logger methods.
    Adding request IDs and correlation IDs, including request method, path, status, and duration.
    Including relevant user/request context while filtering sensitive health or credential data.
    Using JSON logs in production and readable pretty-printing in development.
    Adding LOG_LEVEL to .env.example.
    Testing logging behavior, request context, error handling, and sensitive-data redaction.

    I’ll keep the implementation aligned with the existing Sentry/Datadog setup so the resulting logs are easy to search, correlate, and monitor in production.

  3. grantfox-oss commented on Aug 23, 2026

    @grantfox-oss

    🦊 GrantFox — @Wilfred007 has been assigned to this issue as part of the Third Campaign campaign!

    Next steps:

    1. Open a Pull Request referencing this issue (e.g., Closes #161)
    2. Your PR will be reviewed by the GuardZero144 maintainers

    Good luck! Track your progress on GrantFox.

  4. meshackyaro commented on Aug 23, 2026

    @meshackyaro
    Contributor

    Hi, I'd like to work on this issue. I'd ensure to implement structured logging across the NestJS backend.

    Approach & Technical Implementation

    1. Library Selection & Bootstrap Setup
    • nestjs-pino Integration: Install nestjs-pino and pino-http along with pino-pretty for development. pino offers superior performance compared to Winston, featuring low overhead and native JSON output.
    • NestJS Logger Override: Configure LoggerModule in AppModule and pass app.useLogger(app.get(Logger)) inside backend/src/main.ts to fully replace NestJS's default internal logger.
    1. Contextual Request Logging & Correlation IDs
    • Automatic Request Context: Use pino-http middleware to automatically capture method, url, statusCode, responseTime, and HTTP headers for incoming requests.
    • Correlation IDs: Extract incoming X-Request-ID or X-Correlation-ID headers to bind to the logger context. Fall back to crypto.randomUUID() when headers are absent, ensuring every request has a stable tracking ID.
    • User Context: Bind authenticated user IDs (req.user?.id) dynamically into the request logger context inside the NestJS middleware/interceptor layer.
    1. Environment Formatting & Sensitive Data Redaction
    • Environment-Based Output: Use pino-pretty when NODE_ENV=development (npm run start:dev) for colored, human-readable console output. Switch directly to single-line JSON logs in production (npm run start:prod).
    • Dynamic Log Levels: Map LOG_LEVEL from environment variables (e.g., debug, info, warn, error) defaulting to info.
    • PII & Health Data Redaction: Use Pino’s built-in redact config to prevent leaking sensitive fields. Mask authorization tokens, passwords, and sensitive health records:
    redact: {
      paths: [
        'req.headers.authorization',
        'req.headers.cookie',
        '*.password',
        '*.token',
        '*.healthData',
        '*.ssn',
      ],
      censor: '[REDACTED]',
    }

    Execution Plan

    • Phase 1 (Setup & Configuration): Add nestjs-pino, pino-http, and pino-pretty to package.json. Define LOG_LEVEL in .env.example and wire LoggerModule into backend/src/main.ts and app.module.ts.
    • Phase 2 (Codebase Refactoring): Search and replace all existing console.log, console.error, console.warn, and standard Logger instances across backend/src/ with the injected PinoLogger / Nest JS Logger abstraction.
    • Phase 3 (Redaction & Middleware Testing): Verify sensitive header/body redaction, trace correlation ID assignment through custom middleware, and ensure proper error stack formatting.
    • Phase 4 (Validation): Confirm npm run start:dev streams formatted color logs and npm run start:prod emits valid, queryable single-line JSON objects.

    Ready to take this on as soon as assigned!

  5. grantfox-oss commented on Aug 24, 2026

    @grantfox-oss

    🎉 This issue has been marked as completed on GrantFox as part of the Third Campaign campaign!

    @Wilfred007's PR #174 was approved and merged by @Josie123-Dev.

    🏆 @Wilfred007: You earned 40 FoxPoints for this contribution! Your current tier: Builder (1,068 total points). Track your full progress on GrantFox.

    👏 Great work, @Wilfred007! Keep contributing to GuardZero144.

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

Metadata

Metadata

Assignees

Labels

GrantFox OSSIssue tracked in GrantFox OSSMaybe RewardedIssue may be eligible for a GrantFox rewardThird CampaignCampaign: Third CampaignbackendBackend related issuesdifficulty:hardHard difficulty issuesobservabilityLogging, monitoring, tracingpriority:highHigh priority issues

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions