Skip to content

Conversation

@i-am-that-guy
Copy link
Member

@i-am-that-guy i-am-that-guy commented Dec 23, 2025

  • Introduced a Winston logger for structured logging.
  • Updated errorHandler to log errors using the new logger.
  • Integrated Morgan middleware for HTTP request logging.
  • Added type definitions for Morgan and Winston in package.json and bun.lock.

Summary by CodeRabbit

New Features

  • Implemented comprehensive HTTP request logging throughout the application, capturing request details, timestamps, and related metadata to improve monitoring and provide better visibility into application traffic.
  • Added automatic error logging functionality that records application errors with full context, stack traces, and diagnostic information to enable faster troubleshooting and improve system reliability.

✏️ Tip: You can customize this high-level summary in your review settings.

- Introduced a Winston logger for structured logging.
- Updated errorHandler to log errors using the new logger.
- Integrated Morgan middleware for HTTP request logging.
- Added type definitions for Morgan and Winston in package.json and bun.lock.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 23, 2025

Walkthrough

This pull request introduces HTTP request and error logging by integrating Morgan middleware with Winston logger. New dependencies (morgan, @types/morgan, winston) are added, a logging utility is created, and request/error logging is wired into the application startup and error handling middleware.

Changes

Cohort / File(s) Summary
Package Dependencies
package.json
Added three new dependencies: morgan (HTTP logging middleware), @types/morgan (TypeScript definitions), and winston (logging library)
Logging Infrastructure
src/utils/logger.ts
New module exporting a Winston logger configured with HTTP level, JSON format, and Console transport; includes a .stream adapter for Morgan integration
Application Setup
src/app.ts
Integrated Morgan middleware with a custom LoggerStream class that bridges Morgan logs to Winston logger; invoked with 'combined' format
Error Handling
src/utils/apiError.ts
Added logger import and error logging call (logger.error('ERROR 🔥', err)) in error handling middleware before stack trace processing

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately summarizes the main changes: adding a logger utility and integrating it with error handling and request logging, which aligns with the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch monitoring/logger

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.

@i-am-that-guy i-am-that-guy merged commit dcd51d2 into main Dec 23, 2025
2 of 3 checks passed
Copy link
Contributor

@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: 2

🧹 Nitpick comments (3)
src/utils/apiError.ts (1)

43-43: Enrich error logs with request context.

The error logging lacks contextual information. Consider including request details (method, path, user info) to aid debugging.

🔎 Proposed enhancement
-  logger.error('ERROR 🔥', err);
+  logger.error('ERROR 🔥', {
+    error: err instanceof Error ? err.message : String(err),
+    stack: err instanceof Error ? err.stack : undefined,
+    method: req.method,
+    path: req.path,
+    statusCode: status,
+  });
src/utils/logger.ts (1)

3-17: Consider environment-specific log levels and format consistency.

The logger has two concerns:

  1. The http level logs all HTTP requests, which may be too verbose for production environments.
  2. The console transport overrides the base format (timestamp + JSON) with colorize + simple, which loses timestamps in console output.
🔎 Proposed improvements
 const logger = winston.createLogger({
-  level: "http",
+  level: process.env.NODE_ENV === 'production' ? 'info' : 'http',
   format: winston.format.combine(
     winston.format.timestamp(),
     winston.format.json()
   ),
   transports: [
     new winston.transports.Console({
       format: winston.format.combine(
+        winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
         winston.format.colorize(),
-        winston.format.simple()
+        winston.format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
       )
     })
   ]
 });
src/app.ts (1)

24-24: Consider environment-specific Morgan formats.

The combined format logs extensive details suitable for development but may be overly verbose for production environments.

🔎 Proposed enhancement
-app.use(morgan('combined', { stream: new LoggerStream()}));
+const morganFormat = process.env.NODE_ENV === 'production' ? 'common' : 'combined';
+app.use(morgan(morganFormat, { stream: new LoggerStream() }));
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8284f94 and 2fe7f59.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • package.json
  • src/app.ts
  • src/utils/apiError.ts
  • src/utils/logger.ts
🧰 Additional context used
🧬 Code graph analysis (1)
src/utils/apiError.ts (1)
src/utils/logger.ts (1)
  • logger (25-25)
🔇 Additional comments (3)
src/utils/apiError.ts (1)

2-2: LGTM!

The logger import is correctly added and follows the module structure.

src/app.ts (1)

10-11: LGTM!

The logger and morgan imports are correctly added and properly integrated into the application.

package.json (1)

55-55: Dependencies are current and secure.

Verification confirms:

  • morgan ^1.10.1 is at the latest version (1.10.1)
  • winston ^3.19.0 is at the latest version (3.19.0)
  • @types/morgan ^1.9.10 is at the latest version (1.9.10)

No known security advisories for any of these packages. Historical CVE-2019-5413 (morgan < 1.9.1) does not affect the project since morgan 1.10.1 is in use.

Comment on lines +19 to +23
class LoggerStream {
write(message: string) {
logger.info(message.substring(0, message.lastIndexOf('\n')));
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Add type safety and fix edge case in LoggerStream.

The LoggerStream implementation has two issues:

  1. Missing type annotations for the class
  2. Line 21: lastIndexOf('\n') returns -1 if no newline exists, causing substring(0, -1) to return an empty string
🔎 Proposed fix
-class LoggerStream {
-    write(message: string) {
-        logger.info(message.substring(0, message.lastIndexOf('\n')));
+class LoggerStream {
+    write(message: string): void {
+        logger.info(message.trim());
     }
 }

Note: Using trim() is simpler and handles all trailing whitespace, matching the pattern already used in src/utils/logger.ts line 21.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
class LoggerStream {
write(message: string) {
logger.info(message.substring(0, message.lastIndexOf('\n')));
}
}
class LoggerStream {
write(message: string): void {
logger.info(message.trim());
}
}
🤖 Prompt for AI Agents
In src/app.ts around lines 19 to 23, the LoggerStream class lacks TypeScript
type annotations and its write method uses message.substring(0,
message.lastIndexOf('\n')) which returns an empty string when lastIndexOf
returns -1; change the class to include proper types (e.g., export class
LoggerStream implements NodeJS.WritableStream-like interface or at least
annotate write(message: string): void) and replace the substring logic with a
safe trim of trailing whitespace (e.g., use message.trim() or
message.replace(/\s+$/, '')) before calling logger.info so it never passes an
empty string from a -1 index.

Comment on lines +19 to +23
logger.stream = {
write: (message: any) => {
logger.info(message.trim());
}
} as any;
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Replace type assertions with proper TypeScript interfaces.

The as any type assertion bypasses type safety. Define a proper interface for the stream object.

🔎 Proposed fix
+interface LoggerStream {
+  write(message: string): void;
+}
+
-logger.stream = {
-  write: (message: any) => {
+logger.stream = {
+  write: (message: string) => {
     logger.info(message.trim());
   }
-} as any;
+} as LoggerStream;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
logger.stream = {
write: (message: any) => {
logger.info(message.trim());
}
} as any;
interface LoggerStream {
write(message: string): void;
}
logger.stream = {
write: (message: string) => {
logger.info(message.trim());
}
} as LoggerStream;
🤖 Prompt for AI Agents
In src/utils/logger.ts around lines 19 to 23, the logger.stream assignment uses
an unsafe "as any" cast; define a proper TypeScript interface (e.g., interface
LogStream { write(message: string): void }) or reuse an existing type for stream
objects, update the logger.stream property to be typed with that interface, and
remove the "as any" assertion so the write implementation (calling
logger.info(message.trim())) conforms to the declared type.

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.

2 participants