Property | Default | Description |
---|---|---|
gcpErrorReporting | false | If set to true all error messages are recognized by GCP Error Reporting by wrapping the provided message in a stack trace |
// app.module.ts
import { Module } from '@nestjs/common';
import { LoggingModule } from '@pzwik/nestjs-gcp-logger'; // <-- Import the module
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [
LoggingModule.forRoot({ // <-- Initialize the module
gcpErrorReporting: false // default is 'false'
})
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule { }
// main.ts
import { NestFactory } from '@nestjs/core';
import { LoggingService } from '@pzwik/nestjs-gcp-logger'; // <-- Import here
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule, { bufferLogs: true });
app.useLogger(app.get(LoggingService));
await app.listen(3000);
}
bootstrap();
import { Injectable, Logger } from '@nestjs/common'; // <-- Import Logger from Nest.js
@Injectable()
export class AppService {
private readonly logger = new Logger('AppService');
getHello(): string {
this.logger.error('Some Error happened!'); // <-- Calls the logger
// {"severity":"ERROR","message":"Some Error happened!"}
return 'Hello World!';
}
}
// logger.mock.ts
export class LoggerMock {
log() {
return;
}
error() {
return;
}
warn() {
return;
}
debug() {
return;
}
verbose() {
return;
}
}
// test.spec.ts
const moduleFixture = await Test.createTestingModule({...})
.overrideProvider(LoggingService)
.useClass(LoggerMock)
.compile();
const app = moduleFixture.createNestApplication();
// Do not forget to set the logger, otherwise nestjs default logger
app.useLogger(app.get(LoggingService));
await app.init();
Update module creation
LoggingModule.register()
LoggingModule.forRoot()
Update name of param
GCP_ERROR_REPORTING
gcpErrorReporting
Update how logger passed to app
const app = await NestFactory.create(AppModule, { logger: new LoggingService() });
const app = await NestFactory.create(AppModule, { bufferLogs: true });
app.useLogger(app.get(LoggingService))
Update logger usage in services
import { Injectable, Logger } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
Logger.error('Some Error happened!');
return 'Hello World!';
}
}
import { Injectable, Logger } from '@nestjs/common';
@Injectable()
export class AppService {
private readonly logger = new Logger('AppService');
getHello(): string {
this.logger.error('Some Error happened!');
return 'Hello World!';
}
}
Author: mr-pascal
Source Code: https://github.com/mr-pascal/nestjs-gcp-logging
License: ISC