swaf/src/Logger.ts

41 lines
1.0 KiB
TypeScript

import {Logger as TsLogger} from "tslog";
import {AsyncLocalStorage} from "async_hooks";
import {RequestHandler} from "express";
import {nanoid} from "nanoid";
const requestIdStorage: AsyncLocalStorage<string> = new AsyncLocalStorage();
export const logger = new TsLogger({
requestId: (): string => {
return requestIdStorage.getStore() as string;
},
delimiter: '\t',
maskValuesOfKeys: [
'Authorization',
'password',
'password_confirmation',
'secret',
],
displayFunctionName: false,
displayFilePath: 'hidden',
});
export const loggingContextMiddleware: RequestHandler = (req, res, next) => {
requestIdStorage.run(nanoid(8), () => {
next();
});
};
export const preventContextCorruptionMiddleware = (delegate: RequestHandler): RequestHandler => (
req,
res,
next,
) => {
const data = requestIdStorage.getStore() as string;
delegate(req, res, (err?: Error | 'router') => {
requestIdStorage.enterWith(data);
next(err);
});
};