logctx
Version:
A Pino-based logger with context-aware logging using async_hooks
36 lines (35 loc) • 1.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createContextLogger = void 0;
const Context_1 = require("../Context");
const uuid_1 = require("uuid");
/**
* Middleware to create a context logger for a request.
* It extracts specified headers, query parameters, and cookies,
* and runs the next middleware with the context set.
*
* @param request - The incoming request object.
* @param next - The next middleware function to call.
* @param options - Options to specify which headers, queries, and cookies to include in the context.
*/
function createContextLogger(request, next, options = {}) {
const requestId = request.headers?.['x-request-id'] || (0, uuid_1.v4)();
const headerContext = Object.fromEntries((options.headers || []).map((key) => [key, request.headers?.[key.toLowerCase()]]));
const queryContext = Object.fromEntries((options.queries || []).map((key) => [key, request.query?.[key]]));
const cookieContext = Object.fromEntries((options.cookies || []).map((key) => [key, request.cookies?.[key]]));
const paramContext = Object.fromEntries((options.params || []).map((key) => [key, request.params?.[key]]));
const context = {
requestId: String(requestId),
method: request.method,
path: request.path || request.url,
...headerContext,
...queryContext,
...cookieContext,
...paramContext,
};
console.log('Context created:', context);
(0, Context_1.runWithContext)(context, () => {
next();
});
}
exports.createContextLogger = createContextLogger;