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);
}
});
}
}
+14 -2
View File
@@ -1,9 +1,15 @@
import { Module } from '@nestjs/common';
import {
MiddlewareConsumer,
Module,
NestModule,
RequestMethod,
} from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { KodiApiModule } from './KodiApi/kodi-api.module';
import { StaticModule } from './Static/static.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { LrtCategory } from './KodiApi/LRT/LrtApiClient/Entity/lrt-category.entity';
import { RequestLogMiddleware } from './RequestLog/request-log.middleware';
@Module({
imports: [
@@ -19,4 +25,10 @@ import { LrtCategory } from './KodiApi/LRT/LrtApiClient/Entity/lrt-category.enti
controllers: [],
providers: [],
})
export class AppModule {}
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(RequestLogMiddleware)
.forRoutes({ path: '/*', method: RequestMethod.ALL });
}
}