diff --git a/src/RequestLog/request-log.middleware.ts b/src/RequestLog/request-log.middleware.ts new file mode 100644 index 0000000..67c666a --- /dev/null +++ b/src/RequestLog/request-log.middleware.ts @@ -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); + } + }); + } +} diff --git a/src/app.module.ts b/src/app.module.ts index fd97156..883b6e5 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -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 }); + } +}