To add logging for an Express.js Node app, we use the morgan package.
For instance, we write
const addRequestId = require("express-request-id")({ setHeader: false });
app.use(addRequestId);
const morgan = require("morgan");
morgan.token("id", (req) => req.id.split("-")[0]);
app.use(
morgan("[:date[iso] #:id] Started :method :url for :remote-addr", {
immediate: true,
})
);
app.use(
morgan(
"[:date[iso] #:id] Completed :status :res[content-length] in :response-time ms"
)
);
app.use("/api", router);
to use the express-request-id to add an ID to each request and make it available with the req.id property.
And thenm we call app.use with the middleware returned by morgan.
We call morgan with the format string for each log entry to add logging.