Skip to content

Commit

Permalink
🔊 Middleware for http access log
Browse files Browse the repository at this point in the history
  • Loading branch information
skgndi12 committed Jun 3, 2023
1 parent 9181a7c commit edacbe3
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 6 deletions.
36 changes: 36 additions & 0 deletions api/src/controller/http/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { NextFunction, Request, Response } from 'express';
import { Logger } from 'winston';

import {
CustomError,
InternalErrorType,
NotFoundErrorType
} from '@controller/http/errors';

export class MiddleWare {
constructor(public logger: Logger) {}

public accessLog = (req: Request, res: Response, next: NextFunction) => {
const start = new Date().getTime();
res.on('finish', () => {
if (res.statusCode < 400) {
const end = new Date().getTime();
this.logger.http('Access log', {
method: req.method,
url: req.originalUrl,
addr: req.clientIp,
proto: `${req.protocol}/${req.httpVersion}`,
contentLength: req.headers['content-length'],
userAgent: req.headers['user-agent'],
statusCode: res.statusCode,
bodyBytes: res.getHeader('Content-Length'),
contentType: res.getHeader('Content-Type')?.toString().split(';')[0],
elapsedMs: end - start
});
}
});

next();
};

}
10 changes: 7 additions & 3 deletions api/src/controller/http/server.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
import express from 'express';
import http from 'http';
import requestIp from 'request-ip';
import { Logger } from 'winston';

import { HttpConfig } from '@src/controller/http/types';

import { DevV1Controller } from '@controller/http/dev/dev.v1.controller';
import { MiddleWare } from '@controller/http/middleware';
import { HttpConfig } from '@controller/http/types';

export class HttpServer {
server!: http.Server;

constructor(
private readonly logger: Logger,
private readonly config: HttpConfig
private readonly config: HttpConfig,
private readonly middleware: MiddleWare
) {}

public start = (): Promise<void> => {
return new Promise((resolve) => {
const app = express();
app.use(requestIp.mw());
app.use(this.middleware.accessLog);
app.use('/api', this.getRouters());
this.server = app.listen(this.config.port, () => {
this.logger.info(`HTTP server started on ${this.config.port}`);
Expand Down
12 changes: 9 additions & 3 deletions api/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { MiddleWare } from './controller/http/middleware';

import {
buildHttpConfig,
buildLoggerConfig,
Expand All @@ -17,10 +19,14 @@ async function main() {
}

const logger = loggerInitialize(buildLoggerConfig(config));
const httpServer = new HttpServer(logger, buildHttpConfig(config));
const httpServer = new HttpServer(
logger,
buildHttpConfig(config),
new MiddleWare(logger)
);
await httpServer.start();
await httpServer.close();
logger.info('Server shutdowned');
// await httpServer.close();
// logger.info('Server shutdowned');
}

if (require.main === module) {
Expand Down

0 comments on commit edacbe3

Please sign in to comment.