작성
·
409
0
제목과 동일한 내용으로 logger middleware를 작성하고 app module에 적용하였습니다. 그리고 재시작을 하여 적용 여부를 확인하려 했으나 적용이 되지않은것을 확인했습니다. 어떤부분을 놓치고 있는지 알고싶습니다.
package.json
{
"name": "a-nest",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev-backup": "nest start --watch",
"start:dev": "nest build --webpack --webpackPath webpack-hmr.config.js --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^9.0.0",
"@nestjs/config": "^2.3.0",
"@nestjs/core": "^9.0.0",
"@nestjs/platform-express": "^9.0.0",
"axios": "^1.3.2",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0"
},
"devDependencies": {
"@nestjs/cli": "^9.0.0",
"@nestjs/schematics": "^9.0.0",
"@nestjs/testing": "^9.0.0",
"@types/express": "^4.17.13",
"@types/jest": "28.1.8",
"@types/node": "^16.0.0",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "28.1.3",
"prettier": "^2.3.2",
"run-script-webpack-plugin": "^0.1.1",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "28.0.8",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "4.1.0",
"typescript": "^4.7.4",
"webpack": "^5.75.0",
"webpack-node-externals": "^3.0.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
logger.middleware.ts
import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response, response } from 'express';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
private logger = new Logger('HTTP');
use(req: Request, res: Response, next: NextFunction): void {
const { ip, method, originalUrl } = req;
const userAgent = req.get('user-agent') || '';
response.on('finish', () => {
const { statusCode } = res;
const contentLength = res.get('content-type');
this.logger.log(
`${method} ${originalUrl} ${statusCode} ${contentLength} - ${userAgent} ${ip}`,
);
});
next();
}
}
app.module.ts
import {
MiddlewareConsumer,
Module,
NestModule,
RequestMethod,
} from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule, ConfigService } from '@nestjs/config';
import axios from 'axios';
import { LoggerMiddleware } from './middleware/logger.middleware';
const getEnv = async () => {
// const response = await axios.get('비밀키를 요청하는 url');
// return response.data;
};
const mode = process.env.NODE_ENV || 'development';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [getEnv],
envFilePath: `.env.${mode}`,
}),
],
controllers: [AppController],
providers: [AppService, ConfigService],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): any {
consumer
.apply(LoggerMiddleware)
.forRoutes({ path: '*', method: RequestMethod.ALL });
}
}
nestjs log
Info Webpack is building your sources...
Entrypoint main 47.9 KiB = main.js 46.1 KiB 0.5051cca5f9ad96919687.hot-update.js 1.81 KiB
webpack 5.75.0 compiled successfully in 63 ms
[Nest] 36670 - 02/07/2023, 7:47:49 AM LOG [NestFactory] Starting Nest application... +6659ms
[HMR] Updated modules:
[HMR] - 10
[HMR] - 5
[HMR] - 3
[HMR] Update applied.
[Nest] 36670 - 02/07/2023, 7:47:49 AM LOG [InstanceLoader] ConfigHostModule dependencies initialized +4ms
[Nest] 36670 - 02/07/2023, 7:47:49 AM LOG [InstanceLoader] ConfigModule dependencies initialized +0ms
[Nest] 36670 - 02/07/2023, 7:47:49 AM LOG [InstanceLoader] AppModule dependencies initialized +0ms
[Nest] 36670 - 02/07/2023, 7:47:49 AM LOG [RoutesResolver] AppController {/}: +0ms
[Nest] 36670 - 02/07/2023, 7:47:49 AM LOG [RouterExplorer] Mapped {/, GET} route +1ms
[Nest] 36670 - 02/07/2023, 7:47:49 AM LOG [NestApplication] Nest application successfully started +0ms
적용이 되지않아 생기는 질문이라 에러코드는 없어서 따로 첨부하지 않았습니다.
시도해본 내용
1. localhost:3000 에 직접 접근하였습니다. => return 값은 hi로 지정하여 제대로 받았지만 로그는 뜨지않았습니다.
2. insomnia를 통하여 localhost:3000 에 get요청을 보내어 리턴값은 받았지만 여전히 로그는 찍히지 않았습니다.
```
app.controller.ts
app.service.ts
```