npm package: @relab/nestjs-logging
Description: Logging configuration for Nest.js
Author: Sergey Zwezdin
Latest version: 8.0.1

# @relab/nestjs-logging

## Overview

`@relab/nestjs-logging` provides a robust, flexible logging solution for [NestJS](https://nestjs.com/) applications, powered by [pino](https://getpino.io/#/). It supports both human-friendly "pretty" logs for development and structured JSON logs for production, making it easy to integrate with observability tools like OpenTelemetry Collector.

This package also integrates seamlessly with distributed tracing via `@relab/nestjs-trace-context`, ensuring trace context is included in your logs.

---

## Features

- **Pino-based logging**: Fast, low-overhead, and highly configurable.
- **Pretty or JSON output**: Choose between developer-friendly or machine-readable logs.
- **Trace context propagation**: Automatically includes trace IDs and span IDs in logs.
- **Unhandled error logging**: Simple helpers to log uncaught exceptions and unhandled promise rejections.
- **Custom attributes and resource metadata**: Enrich logs with contextual information.
- **Per-area log levels**: Fine-grained control over log verbosity for different parts of your app.

---

## Installation

```bash
pnpm add @relab/nestjs-logging @relab/nestjs-trace-context pino pino-http pino-pretty
```

---

## Usage

### 1. Main Application Setup

```typescript
// main.ts
import { configureLogger, options as loggerOptions, processUnhandledError } from '@relab/nestjs-logging'

const app = /* create nestjs app */ createApp(/* ... */, { ...loggerOptions })

configureLogger(app)

process.on(
    'uncaughtException',
    processUnhandledError({
        level: 'info',
        layout: process.env.NODE_ENV === 'production' ? 'json' : 'pretty',
    }),
)

process.on(
    'unhandledRejection',
    processUnhandledError({
        level: 'info',
        layout: process.env.NODE_ENV === 'production' ? 'json' : 'pretty',
    }),
)
```

### 2. Module Integration

```typescript
// app.module.ts
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'
import { LoggerModule } from '@relab/nestjs-logging'
import { TraceContextMiddleware, TraceContextModule } from '@relab/nestjs-trace-context'

@Module({
    imports: [
        TraceContextModule,
        LoggerModule.configure({
            level: 'info',
            layout: process.env.NODE_ENV === 'production' ? 'json' : 'pretty',
        }),
    ],
})
export class AppModule implements NestModule {
    configure(consumer: MiddlewareConsumer) {
        consumer.apply(TraceContextMiddleware).forRoutes('*')
    }
}
```

---

## API

### LoggerModule.configure(options)

Registers and configures the logger for your NestJS application.

#### Options

| Name         | Type                                      | Required | Description                                                                                  |
|--------------|-------------------------------------------|----------|----------------------------------------------------------------------------------------------|
| `level`      | `'fatal' \| 'error' \| 'warn' \| 'info' \| 'debug' \| 'trace'` | Yes      | Minimum log level to output.                                                                 |
| `layout`     | `'json'` \| `'pretty'`                    | Yes      | Log output format. Use `'pretty'` for development, `'json'` for production.                  |
| `resource`   | `Record<string, string>`                  | No       | Key-value pairs describing the service/resource (e.g., service name, version, environment).   |
| `attributes` | `(entry: unknown, level: Level) => Record<string, string>` | No | Function to add custom attributes to each log entry.                                         |
| `levels`     | `Record<string, Level>`                   | No       | Per-area log levels. Allows overriding log level for specific logger contexts.               |

#### Example

```typescript
LoggerModule.configure({
    level: 'info',
    layout: 'json',
    resource: { service: 'my-service', version: '1.0.0' },
    attributes: (entry, level) => ({ custom: 'value' }),
    levels: { MyController: 'debug' },
})
```

---

### Other Exports

- **configureLogger(app)**: Sets up the logger instance for your NestJS app.
- **options**: Default options for NestJS app creation (`{ bufferLogs: true }`).
- **processUnhandledError(options)**: Returns a handler for logging uncaught exceptions and unhandled rejections.
- **createLogger(options)**: Creates a standalone pino logger instance with the given options.

---

## Best Practices

- Use `'pretty'` layout for local development to get colorized, readable logs.
- Use `'json'` layout in production for structured logs compatible with log aggregation and observability tools.
- Always include `TraceContextModule` and `TraceContextMiddleware` to enable distributed tracing context in your logs.

---

## License

MIT