Logger
Logger
Nest์๋ ์ธ์คํด์คํ ํ๋ก์ธ์ค ์ค์ ์ฌ์ฉ๋๋ฉฐ ๋ฐ์ํ ์์ธ ๋ฑ๊ณผ ๊ฐ์ ์ฌ๋ฌ ๊ฐ์ง ์ํฉ์์ ์ฌ์ฉ๋๋ ๋ด๋ถ Logger
์ ๊ธฐ๋ณธ ๊ตฌํ์ด ์ ๊ณต๋ฉ๋๋ค. ๊ทธ๋ฌ๋ ๋๋ก๋ ๋ก๊น
์ ์์ ํ ๋นํ์ฑํํ๊ฑฐ๋ ์ฌ์ฉ์ ์ง์ ๊ตฌํ์ ์ ๊ณตํ๊ณ ๋ฉ์์ง๋ฅผ ์ง์ ์ฒ๋ฆฌ ํ ์๋ ์์ต๋๋ค. ๋ก๊ฑฐ๋ฅผ ๋๋ ค๋ฉด Nest์ ์ต์
๊ฐ์ฒด๋ฅผ ์ฌ์ฉํฉ๋๋ค.
const app = await NestFactory.create(ApplicationModule, {
logger: false,
});
await app.listen(3000);
๊ทธ๋ผ์๋ ๋ถ๊ตฌํ๊ณ ์ ์ฒด ๋ก๊น
๋ฉ์ปค๋์ฆ์ ๋นํ์ฑํ ํ๋ ๋์ ๋ค๋ฅธ ๋ก๊ฑฐ๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ด ์ข์ต๋๋ค. ์ด๋ฅผ ์ํด์๋ LoggerService
์ธํฐํ์ด์ค๋ฅผ ๋ง์กฑ์ํค๋ ๊ฐ์ฒด๋ฅผ ์ ๋ฌํด์ผ ํฉ๋๋ค. ์๋ฅผ ๋ค์ด ๋ด์ฅ ์ฝ์
์ด ๋ ์ ์์ต๋๋ค.
const app = await NestFactory.create(ApplicationModule, {
logger: console,
});
await app.listen(3000);
๊ทธ๋ฌ๋ ์ ์ ํ ์์ด๋์ด๋ ์๋๋๋ค. ๊ทธ๋ฌ๋ ์์ฒด ๋ก๊ฑฐ๋ฅผ ์ฝ๊ฒ ๋ง๋ค ์ ์์ต๋๋ค.
import { LoggerService } from '@nestjs/common';
export class MyLogger implements LoggerService {
log(message: string) {}
error(message: string, trace: string) {}
warn(message: string) {}
debug(message: string) {}
verbose(message: string) {}
}
๊ทธ๋ฐ ๋ค์ MyLogger ์ธ์คํด์ค๋ฅผ ์ง์ ์ ์ฉ ํ ์ ์์ต๋๋ค.
const app = await NestFactory.create(ApplicationModule, {
logger: new MyLogger(),
});
await app.listen(3000);
Extend built-in logger
๋ง์ ์ ์ค ์ผ์ด์ค๋ ์์ ์ ๋ก๊ฑฐ๋ฅผ ์์ฑํด์ผ ํฉ๋๋ค. ๋ฐํด๋ฅผ ์์ ํ ์ฌ๋ฐ๋ช
ํ ํ์๋ ์์ต๋๋ค. ๋ด์ฅLogger
ํด๋์ค๋ฅผ ํ์ฅํ์ฌ ๊ธฐ๋ณธ ๊ตฌํ์ ๋ถ๋ถ์ ์ผ๋ก ๋ฌด์ํ๊ณ super
๋ฅผ ์ฌ์ฉํ์ฌ ํธ์ถ์ ๋ถ๋ชจ ํด๋์ค์ ์์ํ์ญ์์ค.
import { Logger } from '@nestjs/common';
export class MyLogger extends Logger {
error(message: string, trace: string) {
// add your tailored logic here
super.error(message, trace);
}
}
Dependency injection
๋ก๊ฑฐ์์ ์์กด์ฑ ์ฃผ์
์ ํ์ฑํํ๋ ค๋ฉด MyLogger ํด๋์ค๋ฅผ ์ค์ ์ ํ๋ฆฌ์ผ์ด์
์ ์ผ๋ถ๋ก ๋ง๋ค์ด์ผํฉ๋๋ค. ์๋ฅผ ๋ค์ด LoggerModule
์ ๋ง๋ค ์ ์์ต๋๋ค.
import { Module } from '@nestjs/common';
import { MyLogger } from './my-logger.service.ts';
@Module({
providers: [MyLogger],
exports: [MyLogger],
})
export class LoggerModule {}
LoggerModule์ ์ด๋์๋ ๊ฐ์ ธ ์ค๋ฉด ํ๋ ์ ์ํฌ๋ ๋ก๊ฑฐ ์ธ์คํด์ค ์์ฑ์ ๋ด๋นํฉ๋๋ค. ์ด์ ๋ถํธ ์คํธ๋ฉ ๋ฐ ์ค๋ฅ ์ฒ๋ฆฌ๋ฅผ ํฌํจํ์ฌ ์ ์ฒด ์ฑ์์ ๋์ผํ ๋ก๊ฑฐ ์ธ์คํด์ค๋ฅผ ์ฌ์ฉํ๋ ค๋ฉด ๋ค์ ๊ตฌ์ฑ์ ์ฌ์ฉํ์ญ์์ค.
const app = await NestFactory.create(ApplicationModule, {
logger: false,
});
app.useLogger(app.get(MyLogger));
await app.listen(3000);
์ด ์๋ฃจ์ ์ ์ ์ผํ ๋จ์ ์ ์ฒซ๋ฒ์งธ ์ด๊ธฐํ ๋ฉ์์ง๊ฐ ๋ก๊ฑฐ ์ธ์คํด์ค์์ ์ฒ๋ฆฌ๋์ง ์์ง๋ง ์ค์ ๋ก๋ ์ค์ํ์ง ์๋ค๋ ๊ฒ์ ๋๋ค.
Last updated
Was this helpful?