Last active
February 15, 2022 14:03
-
-
Save Mualig/533f1ff4810aaa317adf2cde4af45596 to your computer and use it in GitHub Desktop.
NestJS Exception logger filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ArgumentsHost, Catch, HttpException } from '@nestjs/common'; | |
import { BaseExceptionFilter } from '@nestjs/core'; | |
import { Constants } from '../constants.utils'; | |
import { LoggingService } from '../logging/logging.service'; | |
@Catch() | |
export class ExceptionsLoggerFilter extends BaseExceptionFilter { | |
private readonly log; | |
constructor(logger: LoggingService, httpAdapter: any) { | |
super(httpAdapter); | |
this.log = logger.getLogger('ExceptionsLoggerFilter'); | |
} | |
catch(exception: unknown, host: ArgumentsHost) { | |
const uuid: string = host.switchToHttp().getRequest().headers[Constants.correlationId]; | |
if (exception instanceof HttpException) { | |
this.log.warn({ uuid }, `${exception}`); | |
} else { | |
this.log.error({ uuid }, `${exception}`); | |
} | |
super.catch(exception, host); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
async function bootstrap() { | |
... | |
// Use our logger for all Nest logs | |
const logger = await app.resolve(LoggingService); | |
app.useLogger(logger); | |
const { httpAdapter } = app.get(HttpAdapterHost); | |
app.useGlobalFilters(new ExceptionsLoggerFilter(logger, httpAdapter)); | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment