개요
NestJS는 기본적으로 로거가 내장되어 있으며 서비스 클래스나 컨트롤러 클래스에서 로거를 쉽게 사용할 수 있다.
@nestjs/common 패키지에서 Logger 클래스를 불러온 후 인스턴스를 생성하고 logger.log() 나 logger.warn() 등을 사용하면 된다.
@Injectable()
export class AppService {
// Logger 클래스 생성자의 인자로 <클래스명>.name을 넘겨주면 로거의 컨텍스트가 클래스 이름으로 설정된다.
private readonly logger = new Logger(AppService.name);
getHello(): string {
this.logger.debug("Logging...");
return "Hello World!";
}
}
TypeScript
복사
@Injectable({ scope: Scope.TRANSIENT }) // 해당 서비스를 일시적으로 만들며, 각 의존성 주입마다 새로운 인스턴스가 생성
export class CustomLoggerService implements LoggerService {
위처럼 LoggerService의 Scope를 TRANSIENT로 만들었기 때문에
각 서비스에서 해당 LoggerService를 Inject하여 생성하면 각각 서비스마다 다른 인스턴스의 LoggerService를 가지게 된다.
constructor(@Inject(Logger) private readonly logger: LoggerService) {
// 기본 로거 주입 초기화
this.setTarget(this.constructor.name); // 로깅 대상 설정
}
log(message: unknown) {
const input =
typeof message === 'string' || typeof message === 'number'
? message
: JSON.stringify(message);
this.logger.log(input, [this.target]);
}
}
// ProductsService
@Injectable()
export class ProductsService {
constructor(private readonly logger: CustomLoggerService) {
this.logger.setTarget(ProductsService.name);
}
}
// log
[Nest] 7324 - 2024. 10. 26. 오후 2:02:10 LOG [ProductService] {"productName":"zzz","price":1000} // 이렇게 [ProductService] 어떤 로깅 서비스 인스턴스로 출력되는지 알 수 있다.
TypeScript
복사
Winston Logger
Winston 패키지는 로그의 포맷, 파일 형태로 저장 등 로깅을 도와주는 패키지이다.
NestJS에서는 아래 명령어로 패키지를 설치할 수 있다.
npm install winston
Shell
복사
winston 적용해보고 내용 추가 정리 예정