Skip to content

Commit

Permalink
Merge pull request #27 from Open-EO/26-add-request-logging
Browse files Browse the repository at this point in the history
feat(#26): added logging middleware
  • Loading branch information
JanssenBrm authored Mar 14, 2023
2 parents 1df314d + 886c93a commit 883a2eb
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,8 @@
".decorator.ts",
"main.ts",
"bearer.",
".mock.ts"
".mock.ts",
".middleware.ts"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
Expand Down
9 changes: 7 additions & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import { Module } from '@nestjs/common';
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ConfigModule } from './config/config.module';
import { AuthModule } from './auth/auth.module';
import { JobsModule } from './jobs/jobs.module';
import { HealthModule } from './health/health.module';
import { UtilsModule } from './utils/utils.module';
import { LoggerMiddleware } from './middleware/logger.middleware';

@Module({
imports: [ConfigModule, AuthModule, JobsModule, HealthModule, UtilsModule],
})
export class AppModule {}
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): any {
consumer.apply(LoggerMiddleware).forRoutes('*');
}
}
22 changes: 22 additions & 0 deletions src/middleware/logger.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
private logger = new Logger(`HTTP`);
use(req: Request, res: Response, next: NextFunction) {
const startAt = process.hrtime();
const { ip, method, originalUrl } = req;
const userAgent = req.get('user-agent') || '';
res.on('finish', () => {
const { statusCode } = res;
const contentLength = res.get('content-length');
const diff = process.hrtime(startAt);
const responseTime = Math.round(diff[0] * 1e3 + diff[1] * 1e-6);
this.logger.verbose(
`${method} ${originalUrl} ${statusCode} ${responseTime}ms ${contentLength} - ${userAgent} ${ip}`,
);
});
next();
}
}

0 comments on commit 883a2eb

Please sign in to comment.