swaf/src/Logger.ts

41 lines
1.0 KiB
TypeScript
Raw Normal View History

import {AsyncLocalStorage} from "async_hooks";
import {RequestHandler} from "express";
import {nanoid} from "nanoid";
import {Logger as TsLogger} from "tslog";
2020-04-22 15:52:17 +02:00
const requestIdStorage: AsyncLocalStorage<string> = new AsyncLocalStorage();
2020-04-22 15:52:17 +02:00
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;
2021-03-30 12:06:10 +02:00
delegate(req, res, (err?: unknown | 'router') => {
requestIdStorage.enterWith(data);
next(err);
});
};