@josemarinho/nestjs-kibana-logger v1.6.1
Description
Nest A NestJS library for structured logging with Kibana integration using pino-elasticsearch.
Installation
$ npm install @josemarinho/nestjs-kibana-loggerRunning the app
Once the installation process is complete, we can import the LogModule into the root AppModule.
import { Module } from '@nestjs/common';
import { LogModule } from '@josemarinho/nestjs-kibana-logger';
@Module({
imports: [
LogModule.forRoot({
kibanaHost: 'kibana-host',
indexKibana: 'index-kibana'
}),
],
...
})
export class AppModule {}If you use Basic Authentication with username and password or with ApiKey, you can add it to the configuration.
Only use one or the other authentication
import { Module } from '@nestjs/common';
import { LogModule } from '@josemarinho/nestjs-kibana-logger';
@Module({
imports: [
LogModule.forRoot({
kibanaHost: 'elasticsearch-host',
indexKibana: 'index-kibana',
auth: {
username: 'elasticsearch-user',
password: 'elasticsearch-password',
apiKey: 'api-key'
},
}),
],
...
})
export class AppModule {}This solution uses ClsModule to generate a unique traceId for each request, ensuring consistent tracing throughout the application. The TraceIdMiddleware checks for the x-trace-id header or generates a new traceId and stores it in the context. The custom LogService retrieves this traceId from the context and includes it in all log messages for better traceability.
LogModule.forRoot({
// rest of configuration
traceIdHeaderName: 'header-name' // by default is 'x-trace-id'
})Integrating the Log Service in main.ts
To utilize the custom logging functionality provided by your library, the Log service is set as the logger for the NestJS application. Here’s a breakdown:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { LogService } from '@josemarinho/nestjs-kibana-logger';
async function bootstrap() {
const app = await NestFactory.create(AppModule, { bufferLogs: true });
app.useLogger(app.get(LogService));
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();Utilization
The AppService class demonstrates how to use the built-in Logger from NestJS for logging.
import { Injectable, Logger } from '@nestjs/common';
@Injectable()
export class AppService {
private readonly logger = new Logger(AppService.name);
doSomething(): void {
this.logger.log('This is a log message'); // Standard log message
this.logger.warn('This is a warning message'); // Warning message
this.logger.error('This is an error message'); // Error message
}
}After your app it's ready to running.
6 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago