### Install pino-nestjs and pino-http Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Installs the necessary packages for pino-nestjs integration. This includes the core pino-nestjs library and pino-http for HTTP request logging. ```sh npm install pino-nestjs pino-http ``` ```sh pnpm add pino-nestjs pino-http ``` ```sh yarn add pino-nestjs pino-http ``` ```sh bun add pino-nestjs pino-http ``` -------------------------------- ### Configure LoggerModule - Basic Setup Source: https://context7.com/yamcodes/pino-nestjs/llms.txt This snippet shows the basic setup for the LoggerModule in a NestJS application's root module (app.module.ts) and how to apply it to the application instance in main.ts. It imports the LoggerModule and configures the NestJS application to use the pino-nestjs logger. ```typescript import { Module } from '@nestjs/common'; import { LoggerModule } from 'pino-nestjs'; @Module({ imports: [LoggerModule.forRoot()], controllers: [AppController], providers: [AppService], }) export class AppModule {} ``` ```typescript import { NestFactory } from '@nestjs/core'; import { Logger } from 'pino-nestjs'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule, { bufferLogs: true, }); app.useLogger(app.get(Logger)); await app.listen(3000); } bootstrap(); ``` -------------------------------- ### Configure LoggerModule - Asynchronous Setup Source: https://context7.com/yamcodes/pino-nestjs/llms.txt This snippet illustrates an asynchronous configuration for LoggerModule using `forRootAsync`. It imports a `ConfigModule` to provide configuration values like logLevel and appName. The `useFactory` function can perform asynchronous operations before returning the logger configuration object, enabling dynamic setup based on external configurations. ```typescript import { Module, Injectable } from '@nestjs/common'; import { LoggerModule } from 'pino-nestjs'; @Injectable() class ConfigService { public readonly logLevel = 'debug'; public readonly appName = 'my-app'; } @Module({ providers: [ConfigService], exports: [ConfigService], }) class ConfigModule {} @Module({ imports: [ LoggerModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: async (config: ConfigService) => { // Can perform async operations here await someAsyncInitialization(); return { pinoHttp: { name: config.appName, level: config.logLevel, }, }; }, }), ], }) class AppModule {} ``` -------------------------------- ### Use Logger Service - NestJS Compatible API Source: https://context7.com/yamcodes/pino-nestjs/llms.txt This example demonstrates how to use the NestJS-compatible Logger service within a NestJS Injectable class. It shows logging messages at various levels (log, debug, verbose, warn, error) and includes examples of logging plain messages, messages with context, and messages with additional data objects. Error logging includes message, stack trace, and context. ```typescript import { Injectable, Logger } from '@nestjs/common'; @Injectable() export class UserService { private readonly logger = new Logger(UserService.name); async createUser(userData: any) { // Basic log with context this.logger.log('Creating user', UserService.name); // Log with additional data object this.logger.debug('User data received', { userId: userData.id, email: userData.email }); // Log levels: verbose, debug, log, warn, error, fatal this.logger.verbose('Detailed trace information'); this.logger.warn({ operation: 'user_creation', status: 'warning' }); try { const user = await this.userRepository.save(userData); this.logger.log('User created successfully', { userId: user.id }); return user; } catch (error) { // Error logging with stack trace this.logger.error(error.message, error.stack, UserService.name); throw error; } } } // Output (JSON formatted): // {"level":30,"time":1629823318326,"context":"UserService","msg":"Creating user"} // {"level":20,"time":1629823318327,"context":"UserService","userId":"123","email":"user@example.com","msg":"User data received"} ``` -------------------------------- ### Configure LoggerModule - Synchronous with Options Source: https://context7.com/yamcodes/pino-nestjs/llms.txt This example demonstrates configuring the LoggerModule synchronously with various options. It allows customization of pinoHttp middleware, including setting the application name, log level based on NODE_ENV, using 'pino-pretty' for development, and customizing attribute keys. It also shows how to specify routes to log for and exclude specific routes. ```typescript import { Module, RequestMethod } from '@nestjs/common'; import { LoggerModule } from 'pino-nestjs'; @Module({ imports: [ LoggerModule.forRoot({ pinoHttp: [ { name: 'my-app-name', level: process.env.NODE_ENV !== 'production' ? 'debug' : 'info', transport: process.env.NODE_ENV !== 'production' ? { target: 'pino-pretty' } : undefined, customAttributeKeys: { req: 'request', res: 'response', err: 'error', }, }, // Optional: pass a writable stream as second parameter ], forRoutes: [MyController], exclude: [{ method: RequestMethod.ALL, path: 'health' }], renameContext: 'service', }), ], }) class MyModule {} ``` -------------------------------- ### Synchronous Pino NestJS Logger Configuration Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Illustrates synchronous setup of the pino-nestjs logger within a NestJS module, including options for pino-http transport and routing. ```typescript // my.module.ts import { LoggerModule } from 'pino-nestjs'; @Module({ imports: [ LoggerModule.forRoot({ pinoHttp: [ { name: 'my-app-name', level: process.env.NODE_ENV !== 'production' ? 'debug' : 'info', // Install 'pino-pretty' package to use this option transport: process.env.NODE_ENV !== 'production' ? { target: 'pino-pretty' } : undefined, // Other pino-http options: // https://github.com/pinojs/pino-http#api // https://github.com/pinojs/pino/blob/HEAD/docs/api.md#options-object }, someWritableStream ], forRoutes: [MyController], exclude: [{ method: RequestMethod.ALL, path: 'check' }] }) ], // ... }) class MyModule {} ``` -------------------------------- ### Testing with PinoLogger in TypeScript Source: https://context7.com/yamcodes/pino-nestjs/llms.txt Provides an example of how to test a NestJS service that uses PinoLogger. It sets up a testing module, mocks the PinoLogger instance with Jest mock functions, and verifies that the logger methods are called with the expected arguments during service execution. ```typescript import { Test, TestingModule } from '@nestjs/testing'; import { getLoggerToken } from 'pino-nestjs'; import { PaymentService } from './payment.service'; describe('PaymentService', () => { let service: PaymentService; let mockLogger: any; beforeEach(async () => { mockLogger = { trace: jest.fn(), debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(), fatal: jest.fn(), setContext: jest.fn(), }; const module: TestingModule = await Test.createTestingModule({ providers: [ PaymentService, { provide: getLoggerToken(PaymentService.name), useValue: mockLogger, }, ], }).compile(); service = module.get(PaymentService); }); it('should log payment processing', async () => { await service.processPayment({ id: '123', amount: 100 }); expect(mockLogger.debug).toHaveBeenCalledWith( { paymentId: '123' }, 'Processing payment' ); }); }); ``` -------------------------------- ### Extend PinoLogger in a Custom Logger Service (TypeScript) Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Shows how to extend the base PinoLogger class to create a custom logger service in NestJS. It injects PinoLogger and Params, and includes an example of an extended method. ```typescript import { Injectable, Inject } from '@nestjs/common'; import { PinoLogger, Params, PARAMS_PROVIDER_TOKEN } from 'pino-nestjs'; @Injectable() class LoggerService extends PinoLogger { constructor( @Inject(PARAMS_PROVIDER_TOKEN) params: Params ) { super(params); } // Extended method myMethod(): any { this.info('This is a custom method call'); return 'custom method executed'; } } ``` -------------------------------- ### Generate Custom Request ID (TypeScript) Source: https://context7.com/yamcodes/pino-nestjs/llms.txt Provides an example of implementing custom request ID generation in `pino-nestjs` using the `genReqId` option within `LoggerModule.forRoot()`. This function checks for an existing 'X-Request-ID' header and uses it if present, otherwise, it generates a new UUID. This ensures consistent request tracking across logs. ```typescript import { Module } from '@nestjs/common'; import { LoggerModule } from 'pino-nestjs'; import { v4 as uuidv4 } from 'uuid'; @Module({ imports: [ LoggerModule.forRoot({ pinoHttp: { genReqId: (req, res) => { // Use X-Request-ID header if present, otherwise generate UUID return req.headers['x-request-id'] || uuidv4(); }, }, }), ], }) class AppModule {} // Logs will now use custom req.id: // {"level":30,"req":{"id":"550e8400-e29b-41d4-a716-446655440000"},"msg":"request completed"} ``` -------------------------------- ### Reuse Fastify Logger Configuration with useExisting (TypeScript) Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Demonstrates configuring pino-nestjs to reuse the existing Fastify logger configuration using `useExisting: true`. This is useful when Fastify is already set up to handle logging. ```typescript import { Module } from '@nestjs/common'; import { LoggerModule } from 'pino-nestjs'; @Module({ imports: [ LoggerModule.forRoot({ pinoHttp: { useExisting: true, // Other pino-http options can be configured here if needed }, }), ], }) class MyModule {} ``` -------------------------------- ### NestJS Logger Parameter Order Comparison Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Demonstrates the difference in logging parameter order between NestJS's default logger and pino-nestjs. pino-nestjs correctly follows the expected parameter order for NestJS. ```ts // Other loggers - violate NestJS parameter order this.logger.log(context, 'message'); // ❌ context first, message second // With pino-nestjs - respect NestJS parameter order this.logger.log('message', context); // ✅ message first, context second ``` -------------------------------- ### Use Logger in NestJS Service Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Demonstrates how to import and use the Logger from '@nestjs/common' within a NestJS service. It shows various logging levels (verbose, debug, log, warn, error) and how to pass messages and context, including object logging and error handling. This follows NestJS best practices for logger usage. ```typescript // my.service.ts import { Logger } from '@nestjs/common'; export class MyService { private readonly logger = new Logger(MyService.name); foo() { // NestJS parameter order: message first, then context (if needed) this.logger.verbose('My verbose message', MyService.name); this.logger.debug('User data processed', { userId: '123', status: 'success' }); this.logger.log('Operation completed', MyService.name); // Object logging also works with NestJS parameter order this.logger.warn({ operation: 'data_sync', status: 'warning' }, MyService.name); // Error logging try { // Some operation } catch (error) { this.logger.error(error, error.stack, MyService.name); } } } ``` -------------------------------- ### Respect NestJS Parameter Order in Logging Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Demonstrates how pino-nestjs correctly orders log message and context parameters, unlike other loggers, making it a seamless replacement for the default NestJS logger. ```typescript this.logger.log('message', context); // ✅ message first, context second ``` -------------------------------- ### PinoLogger Service - Native Pino API in TypeScript Source: https://context7.com/yamcodes/pino-nestjs/llms.txt Demonstrates using the native Pino logger within a NestJS service to log messages at various levels (trace, debug, info, error). It shows how to inject the logger and pass contextual data as objects alongside the log message. The output format includes request context automatically. ```typescript import { Injectable } from '@nestjs/common'; import { PinoLogger, InjectPinoLogger } from 'pino-nestjs'; @Injectable() export class PaymentService { constructor( @InjectPinoLogger(PaymentService.name) private readonly logger: PinoLogger ) {} async processPayment(paymentData: any) { // Pino native format: object first, message second this.logger.trace({ operation: 'payment_init' }, 'Payment processing started'); // All pino levels available this.logger.debug({ paymentId: paymentData.id }, 'Processing payment'); this.logger.info({ amount: paymentData.amount, currency: 'USD' }, 'Payment validated'); try { const result = await this.gateway.charge(paymentData); this.logger.info({ transactionId: result.id }, 'Payment successful'); return result; } catch (error) { this.logger.error({ err: error }, 'Payment failed'); throw error; } } } // Output includes automatic request context: // {"level":20,"time":1629823792023,"req":{"id":1,"method":"POST","url":"/payment"},"operation":"payment_init","msg":"Payment processing started"} ``` -------------------------------- ### Configure Asynchronous Logging with Pino NestJS Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Details how to enable asynchronous logging with pino-nestjs by configuring `pino.destination` with `sync: false`, which improves performance at the risk of losing logs during system failure. ```typescript // my.module.ts import pino from 'pino'; import { LoggerModule } from 'pino-nestjs'; @Module({ imports: [ LoggerModule.forRoot({ pinoHttp: { stream: pino.destination({ dest: './my-file', // omit for stdout minLength: 4096, // Buffer before writing sync: false, // Asynchronous logging }), }, }), ], // ... }) class MyModule {} ``` -------------------------------- ### Observe Pino JSON Logs in NestJS Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Illustrates the expected JSON output format for logs generated by the pino-nestjs integration. This includes standard application logs, service logs enriched with request context and req.id, and automatic request/response logs. This format facilitates structured logging and analysis. ```json // App logs {"level":30,"time":1629823318326,"pid":14727,"hostname":"my-host","context":"NestFactory","msg":"Starting Nest application..."} {"level":30,"time":1629823318326,"pid":14727,"hostname":"my-host","context":"InstanceLoader","msg":"LoggerModule dependencies initialized"} {"level":30,"time":1629823318327,"pid":14727,"hostname":"my-host","context":"InstanceLoader","msg":"AppModule dependencies initialized"} {"level":30,"time":1629823318327,"pid":14727,"hostname":"my-host","context":"RoutesResolver","msg":"AppController {/}:"} {"level":30,"time":1629823318327,"pid":14727,"hostname":"my-host","context":"RouterExplorer","msg":"Mapped {/, GET} route"} {"level":30,"time":1629823318327,"pid":14727,"hostname":"my-host","context":"NestApplication","msg":"Nest application successfully started"} // Service logs with request context and req.id {"level":10,"time":1629823792023,"pid":15067,"hostname":"my-host","req":{"id":1,"method":"GET","url":"/","query":{},"params":{"0":""},"headers":{"host":"localhost:3000","user-agent":"curl/7.64.1","accept":"*/*"},"remoteAddress":"::1","remotePort":63822},"context":"MyService","foo":"bar","msg":"baz qux"} {"level":20,"time":1629823792023,"pid":15067,"hostname":"my-host","req":{"id":1,"method":"GET","url":"/","query":{},"params":{"0":""},"headers":{"host":"localhost:3000","user-agent":"curl/7.64.1","accept":"*/*"},"remoteAddress":"::1","remotePort":63822},"context":"MyService","msg":"foo bar {\"baz\":\"qux\"}"} {"level":30,"time":1629823792023,"pid":15067,"hostname":"my-host","req":{"id":1,"method":"GET","url":"/","query":{},"params":{"0":""},"headers":{"host":"localhost:3000","user-agent":"curl/7.64.1","accept":"*/*"},"remoteAddress":"::1","remotePort":63822},"context":"MyService","msg":"foo"} // Automatic request/response logs {"level":30,"time":1629823792029,"pid":15067,"hostname":"my-host","req":{"id":1,"method":"GET","url":"/","query":{},"params":{"0":""},"headers":{"host":"localhost:3000","user-agent":"curl/7.64.1","accept":"*/*"},"remoteAddress":"::1","remotePort":63822},"res":{"statusCode":200,"headers":{"x-powered-by":"Express","content-type":"text/html; charset=utf-8","content-length":"12","etag":"W/\"c-Lve95gjOVATpfV8EL5X4nxwjKHE\""}},"responseTime":7,"msg":"request completed"} ``` -------------------------------- ### Directly Use PinoLogger in NestJS Service Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Demonstrates how to inject and use Pino's `PinoLogger` directly within a NestJS service for advanced logging needs, providing access to Pino's full feature set. ```typescript // my.service.ts import { PinoLogger, InjectPinoLogger } from 'pino-nestjs'; export class MyService { constructor( @InjectPinoLogger(MyService.name) private readonly logger: PinoLogger ) {} foo() { // When using PinoLogger directly, use Pino's native format this.logger.trace('This is a trace message'); // Traditional Pino object + message format this.logger.trace({ operation: 'init' }, 'System initialized'); } } ``` -------------------------------- ### Asynchronous Pino NestJS Logger Configuration Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Shows how to configure the pino-nestjs logger asynchronously using a factory function in a NestJS module, allowing for dynamic configuration based on services. ```typescript // my.module.ts import { LoggerModule } from 'pino-nestjs'; @Injectable() class ConfigService { public readonly level = 'debug'; } @Module({ providers: [ConfigService], exports: [ConfigService] }) class ConfigModule {} @Module({ imports: [ LoggerModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: async (config: ConfigService) => { await somePromise(); return { pinoHttp: { level: config.level }, }; } }) ], // ... }) class TestModule {} ``` -------------------------------- ### Asynchronous Logging Configuration in TypeScript Source: https://context7.com/yamcodes/pino-nestjs/llms.txt Configures Pino logger for asynchronous operation within a NestJS application. This is achieved by setting `sync: false` on the Pino destination stream, which buffers logs before writing them to disk, improving application performance at the cost of potential log loss during abrupt shutdowns. ```typescript import { Module } from '@nestjs/common'; import pino from 'pino'; import { LoggerModule } from 'pino-nestjs'; @Module({ imports: [ LoggerModule.forRoot({ pinoHttp: { level: 'info', stream: pino.destination({ dest: './logs/app.log', // omit for stdout minLength: 4096, // Buffer before writing sync: false, // Asynchronous logging for better performance }), }, }), ], }) class AppModule {} ``` -------------------------------- ### Define Pino NestJS Logger Configuration Parameters Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Defines the TypeScript interface for configuring the pino-nestjs logger, including options for pino-http, routing, and renaming the context property. ```typescript interface Params { /** * Optional parameters for `pino-http` module * @see https://github.com/pinojs/pino-http#api */ pinoHttp?: | pinoHttp.Options | DestinationStream | [pinoHttp.Options, DestinationStream]; /** * Optional parameter for routing. Implements interface of * NestJS built-in `MiddlewareConfigProxy['forRoutes']`. * @see https://docs.nestjs.com/middleware#applying-middleware */ forRoutes?: Parameters; /** * Optional parameter for routing. Implements interface of * NestJS built-in `MiddlewareConfigProxy['exclude']`. * @see https://docs.nestjs.com/middleware#applying-middleware */ exclude?: Parameters; /** * Optional parameter to skip pino configuration when using * FastifyAdapter with pre-configured logger. * @see https://github.com/yamcodes/pino-nestjs#faq */ useExisting?: true; /** * Optional parameter to change property name `context` in logs */ renameContext?: string; } ``` -------------------------------- ### Extend Logger and PinoLogger with Custom Methods (TypeScript) Source: https://context7.com/yamcodes/pino-nestjs/llms.txt Demonstrates how to extend the base `Logger` and `PinoLogger` classes provided by `pino-nestjs` to add custom logging methods like `security`, `audit`, and `performance`. This allows for specialized logging within your NestJS application. It requires injecting the `PinoLogger` and `Params` from `pino-nestjs`. ```typescript import { Injectable, Inject } from '@nestjs/common'; import { Logger, PinoLogger, Params, PARAMS_PROVIDER_TOKEN } from 'pino-nestjs'; @Injectable() class CustomLogger extends Logger { constructor( logger: PinoLogger, @Inject(PARAMS_PROVIDER_TOKEN) params: Params ) { super(logger, params); } // Add custom logging methods security(message: string, context?: string) { this.logger.warn({ security: true }, message); } audit(action: string, userId: string, context?: string) { this.logger.info({ audit: true, action, userId }, 'Audit event'); } } @Injectable() class CustomPinoLogger extends PinoLogger { constructor(@Inject(PARAMS_PROVIDER_TOKEN) params: Params) { super(params); } // Add custom methods performance(operation: string, durationMs: number) { this.info({ performance: true, operation, durationMs }, 'Performance metric'); } } // Use in your module @Module({ providers: [CustomLogger], exports: [CustomLogger], imports: [LoggerModule.forRoot()], }) class CustomLoggerModule {} ``` -------------------------------- ### Assigning Extra Fields to Request Context in TypeScript Source: https://context7.com/yamcodes/pino-nestjs/llms.txt Illustrates how to dynamically add extra fields to the request's log context using the `assign` method of PinoLogger in a NestJS controller. These fields will be included in all subsequent log entries for that specific request, simplifying contextual logging. ```typescript import { Controller, Get, Injectable, Logger, Param } from '@nestjs/common'; import { PinoLogger } from 'pino-nestjs'; @Controller('users') class UserController { constructor( private readonly pinoLogger: PinoLogger, private readonly userService: UserService, ) {} @Get(':id') async getUser(@Param('id') userId: string) { // Assign extra fields that will appear in all subsequent logs within this request this.pinoLogger.assign({ userId, tenant: 'acme-corp' }); // All logs from this point will include userId and tenant return this.userService.fetchUser(userId); } } @Injectable() class UserService { private readonly logger = new Logger(UserService.name); async fetchUser(userId: string) { // This log will automatically include { userId, tenant } from assign() this.logger.log('Fetching user data'); const user = await this.repository.findOne(userId); this.logger.log('User found'); return user; } } // Output includes assigned fields: // {"level":30,"time":1629823792023,"req":{"id":1},"userId":"123","tenant":"acme-corp","context":"UserService","msg":"Fetching user data"} // {"level":30,"time":1629823792024,"req":{"id":1},"userId":"123","tenant":"acme-corp","context":"UserService","msg":"User found"} ``` -------------------------------- ### Import LoggerModule in AppModule Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Configures the application module to use the pino-nestjs logger. This is a crucial step for enabling pino logging throughout the NestJS application. ```ts import { LoggerModule } from 'pino-nestjs'; @Module({ imports: [LoggerModule.forRoot()], }) class AppModule {} ``` -------------------------------- ### Use App Logger in main.ts Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Integrates the pino-nestjs logger with the NestJS application instance. This ensures that all application logs will be processed by pino. ```ts import { Logger } from 'pino-nestjs'; const app = await NestFactory.create(AppModule, { bufferLogs: true }); app.useLogger(app.get(Logger)); ``` -------------------------------- ### Test Class with @InjectPinoLogger using Mock Logger (TypeScript) Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Demonstrates how to test a class that injects Pino logger using a mock logger. It utilizes getLoggerToken to provide the mock for dependency injection in testing modules. ```typescript import { Test, TestingModule } from '@nestjs/testing'; import { MyService } from './my.service'; import { getLoggerToken } from 'pino-nestjs'; // Assume mockLogger is defined elsewhere const mockLogger = { /* ... mock logger implementation ... */ }; describe('MyService', () => { let service: MyService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ MyService, { provide: getLoggerToken(MyService.name), useValue: mockLogger, }, ], }).compile(); service = module.get(MyService); }); it('should be defined', () => { expect(service).toBeDefined(); }); }); ``` -------------------------------- ### Configure Runtime Logger Level (TypeScript) Source: https://context7.com/yamcodes/pino-nestjs/llms.txt Shows how to change the log level of all loggers at runtime in a NestJS application using `pino-nestjs`. This is useful for dynamically adjusting logging verbosity based on application needs or debugging requirements. The `PinoLogger.root.level` property can be set to levels like 'trace', 'debug', 'info', 'warn', 'error', or 'fatal'. Disabling logging is achieved by setting the level to 'silent'. ```typescript import { Controller, Post } from '@nestjs/common'; import { PinoLogger } from 'pino-nestjs'; @Controller('admin') class AdminController { @Post('logging/level') setLogLevel(@Body() { level }: { level: string }) { // Change log level at runtime for all loggers PinoLogger.root.level = level; // 'trace', 'debug', 'info', 'warn', 'error', 'fatal' return { message: `Log level changed to ${level}` }; } @Post('logging/disable') disableLogging() { // Disable all logging by setting to silent PinoLogger.root.level = 'silent'; return { message: 'Logging disabled' }; } } ``` -------------------------------- ### Extend Logger in a Custom Logger Service (TypeScript) Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Illustrates extending the base Logger class provided by pino-nestjs, which internally uses PinoLogger. This allows for custom logging logic while leveraging Pino's capabilities. ```typescript import { Injectable, Inject } from '@nestjs/common'; import { Logger, PinoLogger, Params, PARAMS_PROVIDER_TOKEN } from 'pino-nestjs'; @Injectable() class LoggerService extends Logger { constructor( logger: PinoLogger, @Inject(PARAMS_PROVIDER_TOKEN) params: Params ) { super(logger, params); } // Extended method myMethod(): any { this.log('This is a custom method call from extended Logger'); return 'custom method executed'; } } ``` -------------------------------- ### Assign Extra Fields to PinoLogger (TypeScript) Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Shows how to add custom fields to log entries using the `assign` method of PinoLogger. These fields are then included in subsequent log messages from the same logger instance. ```typescript import { Controller, Get } from '@nestjs/common'; import { PinoLogger } from 'pino-nestjs'; import { MyService } from './my.service'; @Controller('/') class TestController { constructor( private readonly logger: PinoLogger, private readonly service: MyService, ) {} @Get() get() { // Assign extra fields in one place... this.logger.assign({ userID: '42' }); return this.service.test(); } } @Injectable() class MyService { // Note: For demonstration, a new Logger instance is created here. // In a real app, this might also be injected. private readonly logger = new PinoLogger(MyService.name); test() { // ...and it will be logged in another place this.logger.log('hello world'); } } ``` -------------------------------- ### Configure LoggerModule for Custom Logger Service (TypeScript) Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Defines a NestJS module that provides a custom LoggerService. It imports the LoggerModule and exports the custom service for use in other parts of the application. ```typescript import { Module } from '@nestjs/common'; import { LoggerService } from './logger.service'; import { LoggerModule } from 'pino-nestjs'; @Module({ providers: [LoggerService], exports: [LoggerService], imports: [ LoggerModule.forRoot({ // Pino configuration options can go here }), ], }) class CustomLoggerModule {} ``` -------------------------------- ### Disable Automatic Request/Response Logs (TypeScript) Source: https://context7.com/yamcodes/pino-nestjs/llms.txt Illustrates how to disable the automatic logging of requests and responses in `pino-nestjs` by configuring the `pinoHttp` options within `LoggerModule.forRoot()`. The `autoLogging` option can be set to `false` to disable all automatic logging, or it can be a function to selectively ignore specific requests based on their URL. ```typescript import { Module } from '@nestjs/common'; import { LoggerModule } from 'pino-nestjs'; @Module({ imports: [ LoggerModule.forRoot({ pinoHttp: { autoLogging: false, // Disable automatic "request completed" logs // Or selectively disable autoLogging: { ignore: (req) => req.url === '/health' || req.url === '/metrics', }, }, }), ], }) class AppModule {} ``` -------------------------------- ### Apply LoggerErrorInterceptor for Detailed Error Logging (TypeScript) Source: https://github.com/yamcodes/pino-nestjs/blob/main/README.md Applies the LoggerErrorInterceptor globally to an application to ensure that stack traces and error class information are exposed in the 'err' property of log messages. ```typescript import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { LoggerErrorInterceptor } from 'pino-nestjs'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalInterceptors(new LoggerErrorInterceptor()); await app.listen(3000); } bootstrap(); ``` -------------------------------- ### Error Interceptor for Detailed Error Logging in TypeScript Source: https://context7.com/yamcodes/pino-nestjs/llms.txt Implements a global error interceptor in NestJS using `LoggerErrorInterceptor` from `pino-nestjs`. This interceptor enhances error logging by automatically including stack traces and error types in the 'err' property of log entries, providing more detailed debugging information. ```typescript import { NestFactory } from '@nestjs/core'; import { Logger, LoggerErrorInterceptor } from 'pino-nestjs'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule, { bufferLogs: true }); app.useLogger(app.get(Logger)); // Add interceptor to expose stack traces and error class in 'err' property app.useGlobalInterceptors(new LoggerErrorInterceptor()); await app.listen(3000); } bootstrap(); // With interceptor, errors will be logged with full details: // {"level":50,"err":{"type":"TypeError","message":"Cannot read property...","stack":"TypeError: Cannot read property...\n at..."},"msg":"Request failed"} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.