2020-11-02 17:48:52 +01:00
|
|
|
import {Logger as TsLogger} from "tslog";
|
2021-01-22 15:54:26 +01:00
|
|
|
import {AsyncLocalStorage} from "async_hooks";
|
|
|
|
import {RequestHandler} from "express";
|
|
|
|
import {nanoid} from "nanoid";
|
2020-04-22 15:52:17 +02:00
|
|
|
|
2021-01-22 15:54:26 +01:00
|
|
|
const requestIdStorage: AsyncLocalStorage<string> = new AsyncLocalStorage();
|
2020-04-22 15:52:17 +02:00
|
|
|
|
2021-01-22 15:54:26 +01:00
|
|
|
export const logger = new TsLogger({
|
|
|
|
requestId: (): string => {
|
|
|
|
return requestIdStorage.getStore() as string;
|
|
|
|
},
|
2021-01-22 16:07:17 +01:00
|
|
|
delimiter: '\t',
|
|
|
|
maskValuesOfKeys: [
|
|
|
|
'Authorization',
|
|
|
|
'password',
|
|
|
|
'password_confirmation',
|
|
|
|
'secret',
|
|
|
|
],
|
|
|
|
displayFunctionName: false,
|
|
|
|
displayFilePath: 'hidden',
|
2021-01-22 15:54:26 +01:00
|
|
|
});
|
|
|
|
|
|
|
|
export const loggingContextMiddleware: RequestHandler = (req, res, next) => {
|
|
|
|
requestIdStorage.run(nanoid(8), () => {
|
|
|
|
next();
|
2020-11-02 17:48:52 +01:00
|
|
|
});
|
2021-01-22 15:54:26 +01:00
|
|
|
};
|
2021-01-24 16:35:33 +01:00
|
|
|
|
|
|
|
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') => {
|
2021-01-24 16:35:33 +01:00
|
|
|
requestIdStorage.enterWith(data);
|
|
|
|
next(err);
|
|
|
|
});
|
|
|
|
};
|