I am using NestJS version 10. I have implemented a custom JSON logger for my application so that all my errors are displayed in JSON format. My main.ts
defines the ussage of the logger like this:
const logger = app.get<LoggingService>(LoggingService);
app.useLogger(logger);
My LoggingService
is defined like this:
@Injectable()
export class LoggingService implements LoggerService { ...
Whenever I want to use the service I use it like this:
import { Logger } from '@nestjs/common';
...
export class MyClass {
private readonly logger = new Logger(MyClass.name);
...
this.logger.error( ...
Using this configuration I’m having the problem that not all errors are using my custom formatting. As some of my providers can throw exceptions inside their constructors, currently those errors won’t use my LoggingService
. In order for my LoggingService
to be used I have to explicitly log the statements with it (as shown in the previous code snippet).
I tried adding the provider constructor logic inside a try{...}catch(){...}
statement but after using the right logger in the catch
and getting the desired JSON formatted error, I still need to throw the error to avoid the application from starting in an undesired state, and this still leads to a non-JSON error log in my app.
I need the exceptions in the right format to have proper visibility of the errors in my cluster observability set-up and I’d like to avoid having non-JSON exceptions laying around.
Any ideas about how to handle this?