create each request logger

This commit is contained in:
Jurgis Sakalauskas
2022-12-08 17:25:27 +02:00
parent a7b53752e6
commit b938f1a3ba
2 changed files with 57 additions and 2 deletions
+43
View File
@@ -0,0 +1,43 @@
import { NestMiddleware } from '@nestjs/common';
import { NextFunction } from 'express';
import { Request, Response } from 'express';
import { appendFile } from 'fs';
import { join } from 'path';
export class RequestLogMiddleware implements NestMiddleware {
async use(req: Request, res: Response, next: NextFunction) {
const strIP = this.extractIp(req);
this.log(strIP + ' ' + req.method + ' ' + decodeURI(req.url));
next();
}
private extractIp(req: Request): string {
let strIP = 'unk_IP';
const strRemoteAddress = req.socket.remoteAddress;
if (strRemoteAddress != undefined) {
strIP = strRemoteAddress.substring(strRemoteAddress.lastIndexOf(':') + 1);
}
if (!strIP || strIP === '1') {
if (req.hostname === 'localhost') {
strIP = '127.0.0.1';
} else {
strIP = 'unk_IP';
}
}
return strIP;
}
private log(message: string) {
const strTime = new Date().toISOString();
const logFile = join(__dirname, process.env.LOG_FILE_REQUESTS);
appendFile(logFile, strTime + ' ' + message + '\n', function (err) {
if (err) {
console.log('error logging ' + message);
console.log(err);
}
});
}
}