Overview
Log all HTTP requests. Essential for debugging and monitoring traffic.
Features
- Morgan integration
- Customizable format
- Skip conditions
- Stream to file
Installation
npx hanma add routes-logger
Dependencies
morgan
Code
import type { Express } from "express";
/** Normalize and clean Express regex paths */
const cleanPath = (path: string): string => {
return (
path
// Remove Express-specific regex tokens
.replace(/\\\//g, "/")
.replace(/\(\?:\^\)\?/g, "")
.replace(/\(\?=\\\/\|\$\)/g, "")
.replace(/\/\?\(\?=\/\|\$\)/g, "") // <- removes /?(?=/|$)
.replace(/\^\?/g, "")
.replace(/\$$/g, "")
// Collapse multiple slashes
.replace(/\/{2,}/g, "/")
// Ensure leading slash
.replace(/^(?!\/)/, "/")
// Remove trailing slash (except root)
.replace(/\/$/, "")
);
};
export const logRoutes = (app: Express) => {
const routes: { method: string; path: string }[] = [];
const extractRoutes = (stack: any, basePath = "") => {
stack.forEach((layer: any) => {
if (layer.route) {
const methods = Object.keys(layer.route.methods).map((m) =>
m.toUpperCase()
);
const fullPath = cleanPath(basePath + layer.route.path);
methods.forEach((method) => routes.push({ method, path: fullPath }));
} else if (layer.name === "router" && layer.handle.stack) {
const match = layer.regexp?.source ?? "";
const prefix = cleanPath(
match.replace("^\\", "/").replace("\\/?(?=\\/|$)", "")
);
extractRoutes(layer.handle.stack, basePath + prefix);
}
});
};
extractRoutes(app._router.stack);
console.log("Registered Routes:");
routes.forEach((r) => console.log(`${r.method.padEnd(6)} ${r.path}`));
};
Usage
import { requestLogger } from './middleware/loggers/routes-logger';
app.use(requestLogger);
Dependencies
morgan
Frequently Asked Questions
How do I install Routes Logger?
Run the following command:
npx hanma add routes-loggerWhat dependencies are required?
This snippet requires: morgan. Make sure to install them before using the snippet.
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to
middleware/loggers/routes-logger.ts.Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.