1
0
mirror of https://github.com/xuthus83/pigallery2.git synced 2025-01-14 14:43:17 +08:00
pigallery2/backend/routes/LoggerRouter.ts

59 lines
1.5 KiB
TypeScript
Raw Normal View History

2018-11-28 23:49:33 +01:00
import {Express, NextFunction, Request, Response} from 'express';
2018-03-30 15:30:30 -04:00
import {Logger} from '../Logger';
2017-06-21 11:32:56 +02:00
2018-11-28 23:49:33 +01:00
declare global {
namespace Express {
interface Request {
_startTime?: number;
logged?: boolean;
}
}
}
2017-07-09 14:23:50 +02:00
/**
* Adds logging to express
*/
2017-06-21 11:32:56 +02:00
export class LoggerRouter {
2018-11-28 23:49:33 +01:00
public static route(app: Express) {
2017-06-21 11:32:56 +02:00
2018-03-30 15:30:30 -04:00
app.get('/api*', (req: Request, res: Response, next: NextFunction) => {
2018-11-28 23:49:33 +01:00
req._startTime = Date.now();
req.logged = true;
2017-06-21 11:32:56 +02:00
const end = res.end;
res.end = (a?: any, b?: any, c?: any) => {
res.end = end;
res.end(a, b, c);
2018-11-28 23:49:33 +01:00
Logger.verbose(req.method, req.url, res.statusCode, (Date.now() - req._startTime) + 'ms');
2017-06-21 11:32:56 +02:00
};
return next();
});
2018-03-30 15:30:30 -04:00
app.get('/node_modules*', (req: Request, res: Response, next: NextFunction) => {
2018-11-28 23:49:33 +01:00
req._startTime = Date.now();
req.logged = true;
2017-06-21 11:32:56 +02:00
const end = res.end;
res.end = (a?: any, b?: any, c?: any) => {
res.end = end;
res.end(a, b, c);
2018-11-28 23:49:33 +01:00
Logger.silly(req.method, req.url, res.statusCode, (Date.now() - req._startTime) + 'ms');
2017-06-21 11:32:56 +02:00
};
return next();
});
app.use((req: Request, res: Response, next: NextFunction) => {
2018-11-28 23:49:33 +01:00
if (req.logged === true) {
2017-06-21 11:32:56 +02:00
return next();
}
2018-11-28 23:49:33 +01:00
req._startTime = Date.now();
2017-06-21 11:32:56 +02:00
const end = res.end;
res.end = (a?: any, b?: any, c?: any) => {
res.end = end;
res.end(a, b, c);
2018-11-28 23:49:33 +01:00
Logger.debug(req.method, req.url, res.statusCode, (Date.now() - req._startTime) + 'ms');
2017-06-21 11:32:56 +02:00
};
return next();
});
}
}