Sunday, 16 January 2022

create request logger in Node.js AsyncLocalStorage

AsyncLocalStorage is a class which creates an asynchronous state within
callbacks and promise chains. It allows us to persist context through
a lifetime of async operations, for example within a web request,
RabbitMQ event or WebSocket message.

we will make our logger inform us about the path of request and time
delta between the request start and log call.


const express = require("express");

const { AsyncLocalStorage } = require("async_hooks");
const { v4: uuid } = require("uuid");

const indexRouter = require("./routes/index");

const app = express();
const context = new AsyncLocalStorage();

function requestLogger(...args) {
const store = context.getStore();
const id = store.get("id");
const timeStart = store.get("timeStart");
const { originalUrl } = store.get("request");
console.log(`${id}, ${originalUrl}, ${+new Date() - timeStart}ms`, args);
}

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use((req, res, next) => {
const store = new Map();
context.run(store, () => {
store.set("id", uuid());
store.set("timeStart", +new Date());
store.set("request", req);
requestLogger("request started");
next();
});
});

app.use("/", indexRouter);

app.use((req, res, next) => {
requestLogger("request ended");
next();
});

module.exports = app;

 

No comments:

Post a Comment