@thecomrado/logger-nestjs
v1.0.0
Published
The The Comrado logger wrapper adapted to Nest.js DI.
Readme
The Comrado Nest.js Logger
Nest.js wrapper around @thecomrado/logger-node for seamless Nest integration.
Install
yarn add @thecomrado/logger-nestjs @thecomrado/logger-node @thecomrado/loggerUsage
Import NestLoggerModule into your root module.
import { NestLoggerModule } from '@thecomrado/logger-nestjs'
@Module({
imports: [NestLoggerModule.forRoot()],
})
export class AppModule {}forRoot options:
application– application name prefixenv– environment (for filtering)
After connecting, you have several options to use the logger.
Inject NestLoggerService
import { NestLoggerService } from '@thecomrado/logger-nestjs'
@Injectable()
export class TestService {
constructor(protected readonly logger: NestLoggerService) {}
test() {
this.logger.log('Start to test my service.')
try {
// Your Business Logic
} catch (error) {
this.logger.error('Error was raised: %o', error)
}
}
}Use the factory
Token NEST_LOGGER_FACTORY provides a factory for creating named loggers.
import { LoggerService } from '@nestjs/common'
import { NEST_LOGGER_FACTORY, NestLoggerFactory } from '@thecomrado/logger-nestjs'
@Injectable()
export class TestService {
protected readonly logger: LoggerService
constructor(@Inject(NEST_LOGGER_FACTORY) loggerFactory: NestLoggerFactory) {
this.logger = loggerFactory('TestService')
}
test() {
this.logger.log('Start to test my service.')
try {
// Your Business Logic
} catch (error) {
this.logger.error('Error was raised: %o', error)
}
}
}Root logger
Use Thecomrado logger as the app’s root logger in bootstrap:
import { NestLoggerService } from '@thecomrado/logger-nestjs'
import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
async function bootstrap(): Promise<void> {
const app = await NestFactory.create(AppModule)
const generalLogger = app.get(NestLoggerService)
app.useLogger(generalLogger)
await app.listen(3000)
}
bootstrap()Example output:
[General] [info] [2024-09-29T07:20:16.556Z] HealthController {/}:
[General] [info] [2024-09-29T07:20:16.559Z] Mapped {/healthz, GET} route
[General] [info] [2024-09-29T07:20:16.559Z] Mapped {/readyz, GET} route
[General] [info] [2024-09-29T07:20:16.560Z] Mapped {/metrics, GET} route
[General] [info] [2024-09-29T07:20:16.563Z] Nest application successfully started