@edirect/logger 11.0.55 → 11.0.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,15 +1,19 @@
1
1
  # @edirect/logger
2
2
 
3
- Structured logging module for eDirect NestJS applications. Built on top of [Pino](https://github.com/pinojs/pino), providing high-performance JSON logging to stdout/stderr, configurable log levels, and correlation ID tracking (sessionId / quoteId).
3
+ Structured logging module for eDirect NestJS applications. Built on top of [Pino](https://github.com/pinojs/pino), providing high-performance JSON logging with AsyncLocalStorage support for automatic context propagation, file output, and seamless integration with NestJS.
4
4
 
5
5
  ## Features
6
6
 
7
- - Structured JSON logs with consistent field names (`message`, `level`, `timestamp`, `name`, `version`)
8
- - Outputs to stdout/stderr
9
- - Configurable log level via environment variable or module options
10
- - Tracks `sessionId` and `quoteId` as correlation context in all log entries
11
- - Global module — register once, inject `LoggerService` anywhere
12
- - Supports both sync (`register`) and async (`registerAsync`) configuration
7
+ - ✅ **Pino-based** - High-performance structured JSON logging
8
+ - ✅ **AsyncLocalStorage** - Automatic context propagation (sessionId, quoteId, correlationId, traceId, userId)
9
+ - ✅ **SINGLETON Architecture** - Better performance
10
+ - ✅ **Multi-level logging** - log, info, warn, error, debug, verbose
11
+ - ✅ **Enhanced error logging** - Multiple overloads with trace support
12
+ - ✅ **File and console output** - Flexible output configuration (stdout/stderr or files)
13
+ - ✅ **Datadog compatible** - ISO 8601 timestamps and structured logs
14
+ - ✅ **NestJS integration** - Native support with middleware
15
+ - ✅ **Global module** - Register once, inject LoggerService anywhere
16
+ - ✅ **Async configuration** - Supports both sync (register) and async (registerAsync) setup
13
17
 
14
18
  ## Installation
15
19
 
@@ -19,9 +23,74 @@ pnpm add @edirect/logger
19
23
  npm install @edirect/logger
20
24
  ```
21
25
 
22
- ## Usage
26
+ ## Quick Start
23
27
 
24
- ### Simple registration (static options)
28
+ ### Basic Usage (Without Middleware)
29
+
30
+ ```typescript
31
+ import { Module } from '@nestjs/common';
32
+ import { LoggerModule } from '@edirect/logger';
33
+
34
+ @Module({
35
+ imports: [LoggerModule],
36
+ })
37
+ export class AppModule {}
38
+ ```
39
+
40
+ ```typescript
41
+ import { Injectable } from '@nestjs/common';
42
+ import { LoggerService } from '@edirect/logger';
43
+
44
+ @Injectable()
45
+ export class MyService {
46
+ constructor(private logger: LoggerService) {}
47
+
48
+ doSomething() {
49
+ this.logger.info('Operation started', { userId: '123' });
50
+ }
51
+ }
52
+ ```
53
+
54
+ ### With Middleware (Automatic Context from HTTP Headers)
55
+
56
+ If you want automatic context extraction from HTTP headers, add the middleware:
57
+
58
+ ```typescript
59
+ import { Module, MiddlewareConsumer, NestModule } from '@nestjs/common';
60
+ import { LoggerModule, LoggerContextMiddleware } from '@edirect/logger';
61
+
62
+ @Module({
63
+ imports: [LoggerModule],
64
+ })
65
+ export class AppModule implements NestModule {
66
+ configure(consumer: MiddlewareConsumer) {
67
+ consumer
68
+ .apply(LoggerContextMiddleware)
69
+ .forRoutes('*'); // Apply to all routes
70
+ }
71
+ }
72
+ ```
73
+
74
+ ### Manual Context Setting
75
+
76
+ ```typescript
77
+ import { Injectable } from '@nestjs/common';
78
+ import { LoggerService } from '@edirect/logger';
79
+
80
+ @Injectable()
81
+ export class MyService {
82
+ constructor(private logger: LoggerService) {}
83
+
84
+ doSomething() {
85
+ this.logger.info('Operation started', { userId: '123' });
86
+ // sessionId and quoteId automatically included from request context!
87
+ }
88
+ }
89
+ ```
90
+
91
+ ## Configuration
92
+
93
+ ### Basic Configuration
25
94
 
26
95
  ```ts
27
96
  import { Module } from '@nestjs/common';
@@ -30,20 +99,26 @@ import { LoggerModule } from '@edirect/logger';
30
99
  @Module({
31
100
  imports: [
32
101
  LoggerModule.register({
33
- output: 'console',
102
+ output: 'console', // 'console' | 'file' | 'both'
34
103
  level: 'info',
104
+ logs: {
105
+ infoFile: './logs/info.log',
106
+ warningFile: './logs/warning.log',
107
+ errorFile: './logs/error.log',
108
+ exceptionsFile: './logs/exceptions.log',
109
+ },
35
110
  name: 'my-service',
111
+ version: '1.0.0',
36
112
  }),
37
113
  ],
38
114
  })
39
115
  export class AppModule {}
40
116
  ```
41
117
 
42
- ### Async registration (with ConfigService)
118
+ ### Async Configuration
43
119
 
44
- ```ts
45
- import { Module } from '@nestjs/common';
46
- import { ConfigModule, ConfigService } from '@edirect/config';
120
+ ```typescript
121
+ import { ConfigService } from '@edirect/config';
47
122
  import { LoggerModule } from '@edirect/logger';
48
123
 
49
124
  @Module({
@@ -51,9 +126,17 @@ import { LoggerModule } from '@edirect/logger';
51
126
  ConfigModule,
52
127
  LoggerModule.registerAsync({
53
128
  imports: [ConfigModule],
54
- useFactory: (configService: ConfigService) => ({
55
- level: (configService.get('LOGS_LEVEL') as any) ?? 'info',
56
- name: configService.get('APP_NAME') ?? 'app',
129
+ useFactory: async (configService: ConfigService) => ({
130
+ output: configService.get('LOGS_OUTPUT'),
131
+ level: configService.get('LOGS_LEVEL'),
132
+ logs: {
133
+ infoFile: configService.get('LOGS_INFO_FILE'),
134
+ warningFile: configService.get('LOGS_WARNING_FILE'),
135
+ errorFile: configService.get('LOGS_ERROR_FILE'),
136
+ exceptionsFile: configService.get('LOGS_EXCEPTIONS_FILE'),
137
+ },
138
+ name: configService.get('APP_NAME'),
139
+ version: configService.get('APP_VERSION'),
57
140
  }),
58
141
  inject: [ConfigService],
59
142
  }),
@@ -62,84 +145,116 @@ import { LoggerModule } from '@edirect/logger';
62
145
  export class AppModule {}
63
146
  ```
64
147
 
65
- ### Inject and use LoggerService
148
+ ## API Reference
66
149
 
67
- ```ts
68
- import { Injectable } from '@nestjs/common';
69
- import { LoggerService } from '@edirect/logger';
150
+ ### Logging Methods
70
151
 
71
- @Injectable()
72
- export class OrderService {
73
- constructor(private readonly logger: LoggerService) {}
74
-
75
- async processOrder(orderId: string, sessionId: string) {
76
- this.logger.setSessionId(sessionId);
77
- this.logger.setQuoteId(orderId);
78
-
79
- this.logger.info('Processing order', JSON.stringify({ orderId }));
80
- try {
81
- // business logic...
82
- this.logger.log('Order processed successfully');
83
- } catch (err) {
84
- this.logger.error('Order processing failed', (err as Error).stack ?? '');
85
- }
86
- }
87
- }
152
+ ```typescript
153
+ // Info logging
154
+ logger.log(message: string, payload?: any);
155
+ logger.info(message: string, payload?: any);
156
+
157
+ // Warning logging
158
+ logger.warn(message: string, payload?: any);
159
+
160
+ // Debug logging
161
+ logger.debug(message: string, payload?: any);
162
+ logger.verbose(message: string, payload?: any);
163
+
164
+ // Error logging (multiple overloads)
165
+ logger.error(message: string); // Just message
166
+ logger.error(message: string, payload: any); // Message + payload to enrich
167
+ logger.error(message: string, trace: string); // Message + stack trace
168
+ logger.error(message: string, error: Error); // Message + Error object
169
+ logger.error(message: string, payload: any, trace: string); // Full context
88
170
  ```
89
171
 
90
- ## API
172
+ ### Context Management
91
173
 
92
- ### `LoggerService` methods
174
+ ```typescript
175
+ // Set context manually (useful for background jobs)
176
+ logger.setContext('sessionId', 'session-123');
177
+ logger.setContext('quoteId', 'quote-456');
178
+ logger.setContext('correlationId', 'corr-789');
179
+ logger.setContext('traceId', 'trace-abc');
180
+ logger.setContext('userId', 'user-xyz');
181
+ ```
93
182
 
94
- | Method | Signature | Description |
95
- | -------------- | ------------------------------------------- | ----------------------------------------------------------- |
96
- | `log` | `(message: string, payload?: string): void` | Alias for `info` |
97
- | `info` | `(message: string, payload?: string): void` | Log at INFO level |
98
- | `warn` | `(message: string, payload?: string): void` | Log at WARN level |
99
- | `error` | `(message: string, trace: string): void` | Log at ERROR level |
100
- | `debug` | `(message: string): void` | Log at DEBUG level |
101
- | `verbose` | `(message: string): void` | Log at VERBOSE level (maps to INFO internally) |
102
- | `setSessionId` | `(sessionId: string): void` | Attach a session ID to all subsequent log entries |
103
- | `setQuoteId` | `(quoteId: string): void` | Attach a quote/correlation ID to all subsequent log entries |
183
+ ### AsyncLocalStorage for Background Jobs
104
184
 
105
- ### `LoggerModuleOptions`
185
+ ```typescript
186
+ import { AsyncContextManager } from '@edirect/logger';
106
187
 
107
- | Option | Type | Default | Description |
108
- | ---------- | ------------ | -------------------------------- | ---------------------------------- |
109
- | `level` | `pino.Level` | `'info'` | Minimum log level |
110
- | `name` | `string` | `npm_package_name \| 'app'` | Service name in every log entry |
111
- | `version` | `string` | `npm_package_version \| '0.0.0'` | Service version in every log entry |
112
- | `host` | `string` | `'0.0.0.0'` | Host tag |
113
- | `protocol` | `string` | `'http'` | Protocol tag |
188
+ @Cron('0 0 * * *')
189
+ handleCron() {
190
+ AsyncContextManager.run({ sessionId: 'cron-job', quoteId: 'batch-001' }, () => {
191
+ this.logger.info('Cron job started');
192
+ // Context automatically propagates through all async calls
193
+ });
194
+ }
195
+ ```
114
196
 
115
- ## Environment Variables
197
+ ## Context Headers
116
198
 
117
- When options are not passed explicitly, the logger reads from environment variables:
199
+ The `LoggerContextMiddleware` automatically extracts context from these HTTP headers:
118
200
 
119
- | Variable | Description | Default |
120
- | --------------- | -------------------------------------------------------------- | -------------------------------- |
121
- | `LOGS_LEVEL` | Log level (`trace`, `debug`, `info`, `warn`, `error`, `fatal`) | `info` |
122
- | `LOGS_HOST` | Host tag in log entries | `0.0.0.0` |
123
- | `LOGS_PROTOCOL` | Protocol tag in log entries | `http` |
124
- | `APP_NAME` | Service name | `npm_package_name` or `app` |
125
- | `APP_VERSION` | Service version | `npm_package_version` or `0.0.0` |
201
+ - `x-session-id` → `sessionId`
202
+ - `x-quote-id` → `quoteId`
203
+ - `x-trace-id` → `traceId`
204
+ - `x-correlation-id` → `correlationId`
205
+ - `req.user.id` → `userId`
126
206
 
127
- ## Log Output Format
207
+ ## Log Format
128
208
 
129
- Every log entry is a JSON object:
209
+ All logs are structured JSON with the following fields:
130
210
 
131
211
  ```json
132
212
  {
213
+ "timestamp": "2024-03-06T14:30:00.123Z",
133
214
  "level": "info",
134
- "timestamp": "2024-01-15T10:30:00.000Z",
135
- "name": "payment-gateway",
136
- "version": "1.2.3",
137
- "host": "pod-abc-123",
215
+ "message": "Operation completed",
216
+ "name": "my-service",
217
+ "version": "1.0.0",
218
+ "host": "localhost",
138
219
  "protocol": "http",
139
- "sessionId": "session-abc-123",
140
- "quoteId": "quote-xyz-456",
141
- "remote-address": "",
142
- "message": "Order created successfully",
143
- "payload": { "orderId": "ORD-789" }
220
+ "sessionId": "session-123",
221
+ "quoteId": "quote-456",
222
+ "correlationId": "corr-789",
223
+ "traceId": "trace-abc",
224
+ "userId": "user-xyz",
225
+ "remote-address": "192.168.1.1",
226
+ "details": { "custom": "data" },
227
+ "trace": "Error stack trace" // Only in error logs
144
228
  }
145
229
  ```
230
+
231
+ ## Error Logging Examples
232
+
233
+ ```typescript
234
+ // Simple error
235
+ logger.error('Something went wrong');
236
+
237
+ // Error with enrichment details
238
+ logger.error('User not found', { userId: '123', action: 'login' });
239
+
240
+ // Error with stack trace
241
+ logger.error('Database error', 'Error: Connection timeout\n at db.connect...');
242
+
243
+ // Error with Error object (auto-extracts stack)
244
+ try {
245
+ throw new Error('Failed to process');
246
+ } catch (error) {
247
+ logger.error('Processing failed', error);
248
+ }
249
+
250
+ // Full context error
251
+ logger.error(
252
+ 'Complex error',
253
+ { context: 'payment', orderId: '456' },
254
+ 'Error stack trace here'
255
+ );
256
+ ```
257
+
258
+ ## License
259
+
260
+ MIT
package/dist/README.md CHANGED
@@ -1,15 +1,19 @@
1
1
  # @edirect/logger
2
2
 
3
- Structured logging module for eDirect NestJS applications. Built on top of [Pino](https://github.com/pinojs/pino), providing high-performance JSON logging to stdout/stderr, configurable log levels, and correlation ID tracking (sessionId / quoteId).
3
+ Structured logging module for eDirect NestJS applications. Built on top of [Pino](https://github.com/pinojs/pino), providing high-performance JSON logging with AsyncLocalStorage support for automatic context propagation, file output, and seamless integration with NestJS.
4
4
 
5
5
  ## Features
6
6
 
7
- - Structured JSON logs with consistent field names (`message`, `level`, `timestamp`, `name`, `version`)
8
- - Outputs to stdout/stderr
9
- - Configurable log level via environment variable or module options
10
- - Tracks `sessionId` and `quoteId` as correlation context in all log entries
11
- - Global module — register once, inject `LoggerService` anywhere
12
- - Supports both sync (`register`) and async (`registerAsync`) configuration
7
+ - ✅ **Pino-based** - High-performance structured JSON logging
8
+ - ✅ **AsyncLocalStorage** - Automatic context propagation (sessionId, quoteId, correlationId, traceId, userId)
9
+ - ✅ **SINGLETON Architecture** - Better performance
10
+ - ✅ **Multi-level logging** - log, info, warn, error, debug, verbose
11
+ - ✅ **Enhanced error logging** - Multiple overloads with trace support
12
+ - ✅ **File and console output** - Flexible output configuration (stdout/stderr or files)
13
+ - ✅ **Datadog compatible** - ISO 8601 timestamps and structured logs
14
+ - ✅ **NestJS integration** - Native support with middleware
15
+ - ✅ **Global module** - Register once, inject LoggerService anywhere
16
+ - ✅ **Async configuration** - Supports both sync (register) and async (registerAsync) setup
13
17
 
14
18
  ## Installation
15
19
 
@@ -19,9 +23,74 @@ pnpm add @edirect/logger
19
23
  npm install @edirect/logger
20
24
  ```
21
25
 
22
- ## Usage
26
+ ## Quick Start
23
27
 
24
- ### Simple registration (static options)
28
+ ### Basic Usage (Without Middleware)
29
+
30
+ ```typescript
31
+ import { Module } from '@nestjs/common';
32
+ import { LoggerModule } from '@edirect/logger';
33
+
34
+ @Module({
35
+ imports: [LoggerModule],
36
+ })
37
+ export class AppModule {}
38
+ ```
39
+
40
+ ```typescript
41
+ import { Injectable } from '@nestjs/common';
42
+ import { LoggerService } from '@edirect/logger';
43
+
44
+ @Injectable()
45
+ export class MyService {
46
+ constructor(private logger: LoggerService) {}
47
+
48
+ doSomething() {
49
+ this.logger.info('Operation started', { userId: '123' });
50
+ }
51
+ }
52
+ ```
53
+
54
+ ### With Middleware (Automatic Context from HTTP Headers)
55
+
56
+ If you want automatic context extraction from HTTP headers, add the middleware:
57
+
58
+ ```typescript
59
+ import { Module, MiddlewareConsumer, NestModule } from '@nestjs/common';
60
+ import { LoggerModule, LoggerContextMiddleware } from '@edirect/logger';
61
+
62
+ @Module({
63
+ imports: [LoggerModule],
64
+ })
65
+ export class AppModule implements NestModule {
66
+ configure(consumer: MiddlewareConsumer) {
67
+ consumer
68
+ .apply(LoggerContextMiddleware)
69
+ .forRoutes('*'); // Apply to all routes
70
+ }
71
+ }
72
+ ```
73
+
74
+ ### Manual Context Setting
75
+
76
+ ```typescript
77
+ import { Injectable } from '@nestjs/common';
78
+ import { LoggerService } from '@edirect/logger';
79
+
80
+ @Injectable()
81
+ export class MyService {
82
+ constructor(private logger: LoggerService) {}
83
+
84
+ doSomething() {
85
+ this.logger.info('Operation started', { userId: '123' });
86
+ // sessionId and quoteId automatically included from request context!
87
+ }
88
+ }
89
+ ```
90
+
91
+ ## Configuration
92
+
93
+ ### Basic Configuration
25
94
 
26
95
  ```ts
27
96
  import { Module } from '@nestjs/common';
@@ -30,20 +99,26 @@ import { LoggerModule } from '@edirect/logger';
30
99
  @Module({
31
100
  imports: [
32
101
  LoggerModule.register({
33
- output: 'console',
102
+ output: 'console', // 'console' | 'file' | 'both'
34
103
  level: 'info',
104
+ logs: {
105
+ infoFile: './logs/info.log',
106
+ warningFile: './logs/warning.log',
107
+ errorFile: './logs/error.log',
108
+ exceptionsFile: './logs/exceptions.log',
109
+ },
35
110
  name: 'my-service',
111
+ version: '1.0.0',
36
112
  }),
37
113
  ],
38
114
  })
39
115
  export class AppModule {}
40
116
  ```
41
117
 
42
- ### Async registration (with ConfigService)
118
+ ### Async Configuration
43
119
 
44
- ```ts
45
- import { Module } from '@nestjs/common';
46
- import { ConfigModule, ConfigService } from '@edirect/config';
120
+ ```typescript
121
+ import { ConfigService } from '@edirect/config';
47
122
  import { LoggerModule } from '@edirect/logger';
48
123
 
49
124
  @Module({
@@ -51,9 +126,17 @@ import { LoggerModule } from '@edirect/logger';
51
126
  ConfigModule,
52
127
  LoggerModule.registerAsync({
53
128
  imports: [ConfigModule],
54
- useFactory: (configService: ConfigService) => ({
55
- level: (configService.get('LOGS_LEVEL') as any) ?? 'info',
56
- name: configService.get('APP_NAME') ?? 'app',
129
+ useFactory: async (configService: ConfigService) => ({
130
+ output: configService.get('LOGS_OUTPUT'),
131
+ level: configService.get('LOGS_LEVEL'),
132
+ logs: {
133
+ infoFile: configService.get('LOGS_INFO_FILE'),
134
+ warningFile: configService.get('LOGS_WARNING_FILE'),
135
+ errorFile: configService.get('LOGS_ERROR_FILE'),
136
+ exceptionsFile: configService.get('LOGS_EXCEPTIONS_FILE'),
137
+ },
138
+ name: configService.get('APP_NAME'),
139
+ version: configService.get('APP_VERSION'),
57
140
  }),
58
141
  inject: [ConfigService],
59
142
  }),
@@ -62,84 +145,116 @@ import { LoggerModule } from '@edirect/logger';
62
145
  export class AppModule {}
63
146
  ```
64
147
 
65
- ### Inject and use LoggerService
148
+ ## API Reference
66
149
 
67
- ```ts
68
- import { Injectable } from '@nestjs/common';
69
- import { LoggerService } from '@edirect/logger';
150
+ ### Logging Methods
70
151
 
71
- @Injectable()
72
- export class OrderService {
73
- constructor(private readonly logger: LoggerService) {}
74
-
75
- async processOrder(orderId: string, sessionId: string) {
76
- this.logger.setSessionId(sessionId);
77
- this.logger.setQuoteId(orderId);
78
-
79
- this.logger.info('Processing order', JSON.stringify({ orderId }));
80
- try {
81
- // business logic...
82
- this.logger.log('Order processed successfully');
83
- } catch (err) {
84
- this.logger.error('Order processing failed', (err as Error).stack ?? '');
85
- }
86
- }
87
- }
152
+ ```typescript
153
+ // Info logging
154
+ logger.log(message: string, payload?: any);
155
+ logger.info(message: string, payload?: any);
156
+
157
+ // Warning logging
158
+ logger.warn(message: string, payload?: any);
159
+
160
+ // Debug logging
161
+ logger.debug(message: string, payload?: any);
162
+ logger.verbose(message: string, payload?: any);
163
+
164
+ // Error logging (multiple overloads)
165
+ logger.error(message: string); // Just message
166
+ logger.error(message: string, payload: any); // Message + payload to enrich
167
+ logger.error(message: string, trace: string); // Message + stack trace
168
+ logger.error(message: string, error: Error); // Message + Error object
169
+ logger.error(message: string, payload: any, trace: string); // Full context
88
170
  ```
89
171
 
90
- ## API
172
+ ### Context Management
91
173
 
92
- ### `LoggerService` methods
174
+ ```typescript
175
+ // Set context manually (useful for background jobs)
176
+ logger.setContext('sessionId', 'session-123');
177
+ logger.setContext('quoteId', 'quote-456');
178
+ logger.setContext('correlationId', 'corr-789');
179
+ logger.setContext('traceId', 'trace-abc');
180
+ logger.setContext('userId', 'user-xyz');
181
+ ```
93
182
 
94
- | Method | Signature | Description |
95
- | -------------- | ------------------------------------------- | ----------------------------------------------------------- |
96
- | `log` | `(message: string, payload?: string): void` | Alias for `info` |
97
- | `info` | `(message: string, payload?: string): void` | Log at INFO level |
98
- | `warn` | `(message: string, payload?: string): void` | Log at WARN level |
99
- | `error` | `(message: string, trace: string): void` | Log at ERROR level |
100
- | `debug` | `(message: string): void` | Log at DEBUG level |
101
- | `verbose` | `(message: string): void` | Log at VERBOSE level (maps to INFO internally) |
102
- | `setSessionId` | `(sessionId: string): void` | Attach a session ID to all subsequent log entries |
103
- | `setQuoteId` | `(quoteId: string): void` | Attach a quote/correlation ID to all subsequent log entries |
183
+ ### AsyncLocalStorage for Background Jobs
104
184
 
105
- ### `LoggerModuleOptions`
185
+ ```typescript
186
+ import { AsyncContextManager } from '@edirect/logger';
106
187
 
107
- | Option | Type | Default | Description |
108
- | ---------- | ------------ | -------------------------------- | ---------------------------------- |
109
- | `level` | `pino.Level` | `'info'` | Minimum log level |
110
- | `name` | `string` | `npm_package_name \| 'app'` | Service name in every log entry |
111
- | `version` | `string` | `npm_package_version \| '0.0.0'` | Service version in every log entry |
112
- | `host` | `string` | `'0.0.0.0'` | Host tag |
113
- | `protocol` | `string` | `'http'` | Protocol tag |
188
+ @Cron('0 0 * * *')
189
+ handleCron() {
190
+ AsyncContextManager.run({ sessionId: 'cron-job', quoteId: 'batch-001' }, () => {
191
+ this.logger.info('Cron job started');
192
+ // Context automatically propagates through all async calls
193
+ });
194
+ }
195
+ ```
114
196
 
115
- ## Environment Variables
197
+ ## Context Headers
116
198
 
117
- When options are not passed explicitly, the logger reads from environment variables:
199
+ The `LoggerContextMiddleware` automatically extracts context from these HTTP headers:
118
200
 
119
- | Variable | Description | Default |
120
- | --------------- | -------------------------------------------------------------- | -------------------------------- |
121
- | `LOGS_LEVEL` | Log level (`trace`, `debug`, `info`, `warn`, `error`, `fatal`) | `info` |
122
- | `LOGS_HOST` | Host tag in log entries | `0.0.0.0` |
123
- | `LOGS_PROTOCOL` | Protocol tag in log entries | `http` |
124
- | `APP_NAME` | Service name | `npm_package_name` or `app` |
125
- | `APP_VERSION` | Service version | `npm_package_version` or `0.0.0` |
201
+ - `x-session-id` → `sessionId`
202
+ - `x-quote-id` → `quoteId`
203
+ - `x-trace-id` → `traceId`
204
+ - `x-correlation-id` → `correlationId`
205
+ - `req.user.id` → `userId`
126
206
 
127
- ## Log Output Format
207
+ ## Log Format
128
208
 
129
- Every log entry is a JSON object:
209
+ All logs are structured JSON with the following fields:
130
210
 
131
211
  ```json
132
212
  {
213
+ "timestamp": "2024-03-06T14:30:00.123Z",
133
214
  "level": "info",
134
- "timestamp": "2024-01-15T10:30:00.000Z",
135
- "name": "payment-gateway",
136
- "version": "1.2.3",
137
- "host": "pod-abc-123",
215
+ "message": "Operation completed",
216
+ "name": "my-service",
217
+ "version": "1.0.0",
218
+ "host": "localhost",
138
219
  "protocol": "http",
139
- "sessionId": "session-abc-123",
140
- "quoteId": "quote-xyz-456",
141
- "remote-address": "",
142
- "message": "Order created successfully",
143
- "payload": { "orderId": "ORD-789" }
220
+ "sessionId": "session-123",
221
+ "quoteId": "quote-456",
222
+ "correlationId": "corr-789",
223
+ "traceId": "trace-abc",
224
+ "userId": "user-xyz",
225
+ "remote-address": "192.168.1.1",
226
+ "details": { "custom": "data" },
227
+ "trace": "Error stack trace" // Only in error logs
144
228
  }
145
229
  ```
230
+
231
+ ## Error Logging Examples
232
+
233
+ ```typescript
234
+ // Simple error
235
+ logger.error('Something went wrong');
236
+
237
+ // Error with enrichment details
238
+ logger.error('User not found', { userId: '123', action: 'login' });
239
+
240
+ // Error with stack trace
241
+ logger.error('Database error', 'Error: Connection timeout\n at db.connect...');
242
+
243
+ // Error with Error object (auto-extracts stack)
244
+ try {
245
+ throw new Error('Failed to process');
246
+ } catch (error) {
247
+ logger.error('Processing failed', error);
248
+ }
249
+
250
+ // Full context error
251
+ logger.error(
252
+ 'Complex error',
253
+ { context: 'payment', orderId: '456' },
254
+ 'Error stack trace here'
255
+ );
256
+ ```
257
+
258
+ ## License
259
+
260
+ MIT
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@edirect/logger",
3
- "version": "11.0.54",
3
+ "version": "11.0.56",
4
4
  "main": "./dist/src/index.js",
5
5
  "types": "./dist/src/index.d.ts",
6
6
  "exports": {
@@ -16,8 +16,8 @@
16
16
  "dist"
17
17
  ],
18
18
  "dependencies": {
19
- "@edirect/config": "^11.0.54",
20
- "@nestjs/common": "^11.1.17",
19
+ "@edirect/config": "^11.0.56",
20
+ "@nestjs/common": "^11.1.19",
21
21
  "pino": "10.3.1",
22
22
  "supertest": "7.2.2",
23
23
  "tslib": "^2.8.1"
@@ -0,0 +1,16 @@
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+ export interface LoggerContext {
3
+ sessionId?: string;
4
+ quoteId?: string;
5
+ userId?: string;
6
+ traceId?: string;
7
+ correlationId?: string;
8
+ [key: string]: any;
9
+ }
10
+ export declare const loggerAsyncStorage: AsyncLocalStorage<LoggerContext>;
11
+ export declare class AsyncContextManager {
12
+ static getContext(): LoggerContext | undefined;
13
+ static setContext(context: LoggerContext): void;
14
+ static run<T>(context: LoggerContext, callback: () => T): T;
15
+ }
16
+ //# sourceMappingURL=async-context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"async-context.d.ts","sourceRoot":"","sources":["../../../src/context/async-context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD,MAAM,WAAW,aAAa;IAC5B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAED,eAAO,MAAM,kBAAkB,kCAAyC,CAAC;AAEzE,qBAAa,mBAAmB;IAC9B,MAAM,CAAC,UAAU,IAAI,aAAa,GAAG,SAAS;IAI9C,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,aAAa,GAAG,IAAI;IAK/C,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAC;CAG5D"}
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AsyncContextManager = exports.loggerAsyncStorage = void 0;
4
+ const async_hooks_1 = require("async_hooks");
5
+ exports.loggerAsyncStorage = new async_hooks_1.AsyncLocalStorage();
6
+ class AsyncContextManager {
7
+ static getContext() {
8
+ return exports.loggerAsyncStorage.getStore();
9
+ }
10
+ static setContext(context) {
11
+ const current = exports.loggerAsyncStorage.getStore() || {};
12
+ exports.loggerAsyncStorage.enterWith({ ...current, ...context });
13
+ }
14
+ static run(context, callback) {
15
+ return exports.loggerAsyncStorage.run(context, callback);
16
+ }
17
+ }
18
+ exports.AsyncContextManager = AsyncContextManager;
@@ -1,4 +1,6 @@
1
+ export * from './context/async-context';
1
2
  export * from './logger/logger.class';
2
3
  export * from './logger/logger.module';
3
4
  export * from './logger/logger.service';
5
+ export * from './middleware/logger-context.middleware';
4
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,cAAc,wBAAwB,CAAC;AACvC,cAAc,yBAAyB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,wBAAwB,CAAC;AACvC,cAAc,yBAAyB,CAAC;AACxC,cAAc,wCAAwC,CAAC"}
package/dist/src/index.js CHANGED
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./context/async-context"), exports);
4
5
  tslib_1.__exportStar(require("./logger/logger.class"), exports);
5
6
  tslib_1.__exportStar(require("./logger/logger.module"), exports);
6
7
  tslib_1.__exportStar(require("./logger/logger.service"), exports);
8
+ tslib_1.__exportStar(require("./middleware/logger-context.middleware"), exports);
@@ -1,16 +1,19 @@
1
1
  import { Level } from 'pino';
2
2
  export interface LoggerModuleOptions {
3
- output?: string;
3
+ output?: 'console' | 'file' | 'both';
4
4
  logs?: {
5
5
  errorFile: string;
6
6
  warningFile: string;
7
7
  infoFile: string;
8
8
  exceptionsFile?: string;
9
+ minLength?: number;
10
+ sync?: boolean;
9
11
  };
10
12
  name?: string;
11
13
  host?: string;
12
14
  protocol?: string;
13
15
  version?: string;
14
16
  level?: Level;
17
+ payloadFieldName?: 'details' | 'payload';
15
18
  }
16
19
  //# sourceMappingURL=logger-module-options.interface.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger-module-options.interface.d.ts","sourceRoot":"","sources":["../../../../src/logger/interfaces/logger-module-options.interface.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,MAAM,CAAC;AAE7B,MAAM,WAAW,mBAAmB;IAClC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE;QACL,SAAS,EAAE,MAAM,CAAC;QAClB,WAAW,EAAE,MAAM,CAAC;QACpB,QAAQ,EAAE,MAAM,CAAC;QACjB,cAAc,CAAC,EAAE,MAAM,CAAC;KACzB,CAAC;IACF,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,KAAK,CAAC;CACf"}
1
+ {"version":3,"file":"logger-module-options.interface.d.ts","sourceRoot":"","sources":["../../../../src/logger/interfaces/logger-module-options.interface.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,MAAM,CAAC;AAE7B,MAAM,WAAW,mBAAmB;IAClC,MAAM,CAAC,EAAE,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC;IACrC,IAAI,CAAC,EAAE;QACL,SAAS,EAAE,MAAM,CAAC;QAClB,WAAW,EAAE,MAAM,CAAC;QACpB,QAAQ,EAAE,MAAM,CAAC;QACjB,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,IAAI,CAAC,EAAE,OAAO,CAAC;KAChB,CAAC;IACF,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,gBAAgB,CAAC,EAAE,SAAS,GAAG,SAAS,CAAC;CAC1C"}
@@ -1,13 +1,17 @@
1
+ import { LoggerContext } from '../context/async-context';
1
2
  import { LoggerModuleOptions } from './interfaces/logger-module-options.interface';
2
3
  export interface LogMetadata {
3
- 'remote-address': string;
4
- sessionId: string;
5
- quoteId: string;
4
+ 'remote-address'?: string;
5
+ sessionId?: string;
6
+ quoteId?: string;
7
+ correlationId?: string;
8
+ traceId?: string;
9
+ userId?: string;
10
+ details?: any;
6
11
  payload?: any;
12
+ trace?: string;
7
13
  }
8
14
  export declare class Logger {
9
- private sessionId;
10
- private quoteId;
11
15
  private configs;
12
16
  private logger;
13
17
  constructor(env: Record<string, string>, options?: LoggerModuleOptions);
@@ -15,10 +19,11 @@ export declare class Logger {
15
19
  info(message: string, payload?: any, remoteAddress?: string): void;
16
20
  warning(message: string, payload?: any, remoteAddress?: string): void;
17
21
  warn(message: string, payload?: any, remoteAddress?: string): void;
18
- error(message: string | Error | unknown, payload?: any, remoteAddress?: string): void;
19
- verbose(message: string, remoteAddress?: string): void;
20
- setSessionId(sessionId: string): void;
21
- setQuoteId(quoteId: string): void;
22
+ error(message: string, trace?: string, remoteAddress?: string): void;
23
+ error(message: string, error: Error, remoteAddress?: string): void;
24
+ error(message: string, payload: any, trace?: string, remoteAddress?: string): void;
25
+ verbose(message: string, payload?: any, remoteAddress?: string): void;
26
+ setContext(key: keyof LoggerContext, value: string): void;
22
27
  private buildLog;
23
28
  }
24
29
  //# sourceMappingURL=log.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"log.d.ts","sourceRoot":"","sources":["../../../src/logger/log.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mBAAmB,EAAE,MAAM,8CAA8C,CAAC;AAEnF,MAAM,WAAW,WAAW;IAC1B,gBAAgB,EAAE,MAAM,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,GAAG,CAAC;CACf;AAED,qBAAa,MAAM;IACjB,OAAO,CAAC,SAAS,CAAM;IACvB,OAAO,CAAC,OAAO,CAAM;IACrB,OAAO,CAAC,OAAO,CAAsB;IACrC,OAAO,CAAC,MAAM,CAAe;gBAEjB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,CAAC,EAAE,mBAAmB;IAyGtE,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI;IAInE,IAAI,CAAC,OAAO,EAAE,MA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able @typescript-eslint/no-explicit-any */
6
5
  const pino_1 = tslib_1.__importStar(require("pino"));
6
+ const async_context_1 = require("../context/async-context");
7
7
  class Logger {
8
- sessionId = '';
9
- quoteId = '';
10
8
  configs;
11
9
  logger;
12
10
  constructor(env, options) {
@@ -23,6 +21,7 @@ class Logger {
23
21
  version: env.npm_package_version ?? env.APP_VERSION ?? '0.0.0',
24
22
  host: env.LOGS_HOST ?? '0.0.0.0',
25
23
  protocol: env.LOGS_PROTOCOL ?? 'http',
24
+ payloadFieldName: env.LOGS_PAYLOAD_FIELD_NAME ?? 'payload',
26
25
  };
27
26
  this.configs = { ...defaults, ...options };
28
27
  const streams = [];
@@ -33,7 +32,8 @@ class Logger {
33
32
  stream: pino_1.default.destination({
34
33
  dest: this.configs.logs.infoFile,
35
34
  mkdir: true,
36
- sync: false,
35
+ sync: this.configs.logs.sync ?? false,
36
+ minLength: this.configs.logs.minLength ?? 4096,
37
37
  }),
38
38
  });
39
39
  }
@@ -43,7 +43,8 @@ class Logger {
43
43
  stream: pino_1.default.destination({
44
44
  dest: this.configs.logs.warningFile,
45
45
  mkdir: true,
46
- sync: false,
46
+ sync: this.configs.logs.sync ?? false,
47
+ minLength: this.configs.logs.minLength ?? 4096,
47
48
  }),
48
49
  });
49
50
  }
@@ -53,7 +54,8 @@ class Logger {
53
54
  stream: pino_1.default.destination({
54
55
  dest: this.configs.logs.errorFile,
55
56
  mkdir: true,
56
- sync: false,
57
+ sync: this.configs.logs.sync ?? false,
58
+ minLength: this.configs.logs.minLength ?? 4096,
57
59
  }),
58
60
  });
59
61
  }
@@ -66,7 +68,7 @@ class Logger {
66
68
  }
67
69
  this.logger = (0, pino_1.default)({
68
70
  level: this.configs.level,
69
- timestamp: () => `,"timestamp":"${new Date(Date.now()).toISOString()}"`,
71
+ timestamp: () => `,"timestamp":"${new Date().toISOString()}"`,
70
72
  messageKey: 'message',
71
73
  errorKey: 'error',
72
74
  base: {
@@ -82,7 +84,7 @@ class Logger {
82
84
  if (this.configs.logs?.exceptionsFile) {
83
85
  const exceptionLogger = (0, pino_1.default)({
84
86
  level: 'fatal',
85
- timestamp: () => `,"timestamp":"${new Date(Date.now()).toISOString()}"`,
87
+ timestamp: () => `,"timestamp":"${new Date().toISOString()}"`,
86
88
  messageKey: 'message',
87
89
  errorKey: 'error',
88
90
  }, pino_1.default.destination({
@@ -112,33 +114,65 @@ class Logger {
112
114
  warn(message, payload, remoteAddress) {
113
115
  this.warning(message, payload, remoteAddress);
114
116
  }
115
- error(message, payload, remoteAddress) {
116
- if (message instanceof Error) {
117
- const errorPayload = payload !== undefined
118
- ? { name: message.name, stack: message.stack, detail: payload }
119
- : { name: message.name, stack: message.stack };
120
- this.logger.error(this.buildLog(errorPayload, remoteAddress), message.message);
117
+ error(message, traceOrErrorOrPayload, traceOrRemoteAddress, remoteAddress) {
118
+ let finalTrace;
119
+ let finalPayload;
120
+ let finalRemoteAddress = '';
121
+ let finalMessage = message;
122
+ if (typeof message !== 'string') {
123
+ finalPayload = message;
124
+ finalMessage = message?.message || 'Error';
121
125
  }
122
- else {
123
- this.logger.error(this.buildLog(payload, remoteAddress), String(message ?? ''));
126
+ if (traceOrErrorOrPayload instanceof Error) {
127
+ finalTrace = traceOrErrorOrPayload.stack || traceOrErrorOrPayload.message;
128
+ finalRemoteAddress = traceOrRemoteAddress || '';
124
129
  }
130
+ else if (typeof traceOrErrorOrPayload === 'string') {
131
+ finalTrace = traceOrErrorOrPayload;
132
+ finalRemoteAddress = traceOrRemoteAddress || '';
133
+ }
134
+ else if (traceOrErrorOrPayload !== undefined && typeof traceOrRemoteAddress === 'string' && remoteAddress !== undefined) {
135
+ finalPayload = finalPayload || traceOrErrorOrPayload;
136
+ finalTrace = traceOrRemoteAddress;
137
+ finalRemoteAddress = remoteAddress;
138
+ }
139
+ else if (traceOrErrorOrPayload !== undefined && typeof traceOrRemoteAddress === 'string') {
140
+ finalPayload = finalPayload || traceOrErrorOrPayload;
141
+ finalTrace = traceOrRemoteAddress;
142
+ }
143
+ else if (traceOrErrorOrPayload !== undefined) {
144
+ finalPayload = finalPayload || traceOrErrorOrPayload;
145
+ }
146
+ this.logger.error(this.buildLog(finalPayload, finalRemoteAddress, finalTrace), finalMessage);
125
147
  }
126
- verbose(message, remoteAddress) {
127
- this.info(message, remoteAddress);
128
- }
129
- setSessionId(sessionId) {
130
- this.sessionId = sessionId;
148
+ verbose(message, payload, remoteAddress) {
149
+ this.info(message, payload, remoteAddress);
131
150
  }
132
- setQuoteId(quoteId) {
133
- this.quoteId = quoteId;
151
+ setContext(key, value) {
152
+ async_context_1.AsyncContextManager.setContext({ [key]: value });
134
153
  }
135
- buildLog(payload, remoteAddress = '') {
136
- return {
137
- sessionId: this.sessionId,
138
- quoteId: this.quoteId,
139
- 'remote-address': remoteAddress,
140
- payload,
141
- };
154
+ buildLog(payload, remoteAddress = '', trace) {
155
+ const context = async_context_1.AsyncContextManager.getContext();
156
+ const metadata = {};
157
+ if (context?.sessionId)
158
+ metadata.sessionId = context.sessionId;
159
+ if (context?.quoteId)
160
+ metadata.quoteId = context.quoteId;
161
+ if (context?.correlationId)
162
+ metadata.correlationId = context.correlationId;
163
+ if (context?.traceId)
164
+ metadata.traceId = context.traceId;
165
+ if (context?.userId)
166
+ metadata.userId = context.userId;
167
+ if (remoteAddress)
168
+ metadata['remote-address'] = remoteAddress;
169
+ if (payload !== undefined) {
170
+ const fieldName = this.configs.payloadFieldName ?? 'payload';
171
+ metadata[fieldName] = payload;
172
+ }
173
+ if (trace)
174
+ metadata.trace = trace;
175
+ return metadata;
142
176
  }
143
177
  }
144
178
  exports.Logger = Logger;
@@ -4,13 +4,14 @@ import { Logger as LoggerImpl } from './log';
4
4
  export declare class Logger implements LoggerService {
5
5
  private logger;
6
6
  constructor(env: Record<string, string>, clientConfigs?: LoggerModuleOptions, logger?: LoggerImpl);
7
- setSessionId(sessionId: string): void;
8
- setQuoteId(quoteId: string): void;
9
- log(message: string, payload?: string): void;
10
- info(message: string, payload?: string): void;
11
- error(message: unknown, trace?: unknown): void;
12
- warn(message: string, payload?: string): void;
13
- debug(message: string): void;
14
- verbose(message: string): void;
7
+ setContext(key: string, value: string): void;
8
+ log(message: string, payload?: any): void;
9
+ info(message: string, payload?: any): void;
10
+ error(message: string, trace?: string, remoteAddress?: string): void;
11
+ error(message: string, error: Error, remoteAddress?: string): void;
12
+ error(message: string, payload: any, trace?: string, remoteAddress?: string): void;
13
+ warn(message: string, payload?: any): void;
14
+ debug(message: string, payload?: any): void;
15
+ verbose(message: string, payload?: any): void;
15
16
  }
16
17
  //# sourceMappingURL=logger.class.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger.class.d.ts","sourceRoot":"","sources":["../../../src/logger/logger.class.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAE/C,OAAO,EAAE,mBAAmB,EAAE,MAAM,8CAA8C,CAAC;AACnF,OAAO,EAAE,MAAM,IAAI,UAAU,EAAE,MAAM,OAAO,CAAC;AAE7C,qBAAa,MAAO,YAAW,aAAa;IAIxC,OAAO,CAAC,MAAM;gBAFd,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC3B,aAAa,CAAC,EAAE,mBAAmB,EAC3B,MAAM,aAAqC;IAGrD,YAAY,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;IAIrC,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAIjC,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI;IAI5C,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI;IAI7C,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,OAAO,GAAG,IAAI;IAQ9C,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI;IAI7C,KAAK,CAAC,OAA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AI3C,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,GAAG,IAAI;CAG9C"}
@@ -7,34 +7,26 @@ class Logger {
7
7
  constructor(env, clientConfigs, logger = new log_1.Logger(env, clientConfigs)) {
8
8
  this.logger = logger;
9
9
  }
10
- setSessionId(sessionId) {
11
- this.logger.setSessionId(sessionId);
12
- }
13
- setQuoteId(quoteId) {
14
- this.logger.setQuoteId(quoteId);
10
+ setContext(key, value) {
11
+ this.logger.setContext(key, value);
15
12
  }
16
13
  log(message, payload) {
17
- this.logger.info(message, payload || '');
14
+ this.logger.info(message, payload);
18
15
  }
19
16
  info(message, payload) {
20
- this.logger.info(message, payload || '');
17
+ this.logger.info(message, payload);
21
18
  }
22
- error(message, trace) {
23
- if (message instanceof Error) {
24
- this.logger.error(message.message, trace ?? message.stack);
25
- }
26
- else {
27
- this.logger.error(String(message ?? ''), trace);
28
- }
19
+ error(message, traceOrErrorOrPayload, traceOrRemoteAddress, remoteAddress) {
20
+ this.logger.error(message, traceOrErrorOrPayload, traceOrRemoteAddress, remoteAddress);
29
21
  }
30
22
  warn(message, payload) {
31
- this.logger.warn(message, payload || '');
23
+ this.logger.warn(message, payload);
32
24
  }
33
- debug(message) {
34
- this.logger.debug(message);
25
+ debug(message, payload) {
26
+ this.logger.debug(message, payload);
35
27
  }
36
- verbose(message) {
37
- this.logger.verbose(message);
28
+ verbose(message, payload) {
29
+ this.logger.verbose(message, payload);
38
30
  }
39
31
  }
40
32
  exports.Logger = Logger;
@@ -1 +1 @@
1
- {"version":3,"file":"logger.module.d.ts","sourceRoot":"","sources":["../../../src/logger/logger.module.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAkB,MAAM,gBAAgB,CAAC;AAI/D,OAAO,EACL,uBAAuB,EACvB,kBAAkB,EAClB,YAAY,EACb,MAAM,4BAA4B,CAAC;AAGpC,qBAKa,YAAa,SAAQ,uBAAuB;IACvD,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,OAAO,YAAY,GAAG,aAAa;IAM5D,MAAM,CAAC,aAAa,CAAC,OAAO,EAAE,OAAO,kBAAkB,GAAG,aAAa;CAKxE"}
1
+ {"version":3,"file":"logger.module.d.ts","sourceRoot":"","sources":["../../../src/logger/logger.module.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAkB,MAAM,gBAAgB,CAAC;AAK/D,OAAO,EACL,uBAAuB,EACvB,kBAAkB,EAClB,YAAY,EACb,MAAM,4BAA4B,CAAC;AAGpC,qBAKa,YAAa,SAAQ,uBAAuB;IACvD,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,OAAO,YAAY,GAAG,aAAa;IAM5D,MAAM,CAAC,aAAa,CAAC,OAAO,EAAE,OAAO,kBAAkB,GAAG,aAAa;CAKxE"}
@@ -4,6 +4,7 @@ exports.LoggerModule = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const common_1 = require("@nestjs/common");
6
6
  const config_1 = require("@edirect/config");
7
+ const logger_context_middleware_1 = require("../middleware/logger-context.middleware");
7
8
  const logger_service_1 = require("./logger.service");
8
9
  const logger_module_definition_1 = require("./logger.module.definition");
9
10
  // TODO For TODO changes check the documentation: https://docs.nestjs.com/fundamentals/dynamic-modules
@@ -23,7 +24,7 @@ exports.LoggerModule = LoggerModule;
23
24
  exports.LoggerModule = LoggerModule = tslib_1.__decorate([
24
25
  (0, common_1.Global)(),
25
26
  (0, common_1.Module)({
26
- providers: [logger_service_1.LoggerService, config_1.ConfigService],
27
- exports: [logger_service_1.LoggerService],
27
+ providers: [logger_service_1.LoggerService, config_1.ConfigService, logger_context_middleware_1.LoggerContextMiddleware],
28
+ exports: [logger_service_1.LoggerService, logger_context_middleware_1.LoggerContextMiddleware],
28
29
  })
29
30
  ], LoggerModule);
@@ -5,13 +5,14 @@ export declare class LoggerService {
5
5
  private options?;
6
6
  private readonly logger;
7
7
  constructor(configService: ConfigService, options?: LoggerModuleOptions | undefined);
8
- setSessionId(sessionId: string): void;
9
- setQuoteId(quoteId: string): void;
10
- log(message: string, payload?: string): void;
11
- info(message: string, payload?: string): void;
12
- error(message: string | Error | unknown, trace?: string): void;
13
- warn(message: string, payload?: string): void;
14
- debug(message: string): void;
15
- verbose(message: string): void;
8
+ setContext(key: string, value: string): void;
9
+ log(message: string, payload?: any): void;
10
+ info(message: string, payload?: any): void;
11
+ error(message: string, trace?: string, remoteAddress?: string): void;
12
+ error(message: string, error: Error, remoteAddress?: string): void;
13
+ error(message: string, payload: any, trace?: string, remoteAddress?: string): void;
14
+ warn(message: string, payload?: any): void;
15
+ debug(message: string, payload?: any): void;
16
+ verbose(message: string, payload?: any): void;
16
17
  }
17
18
  //# sourceMappingURL=logger.service.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger.service.d.ts","sourceRoot":"","sources":["../../../src/logger/logger.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAGhD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,8CAA8C,CAAC;AAIxF,qBACa,aAAa;IAIC,OAAO,CAAC,QAAQ,CAAC,aAAa;IAGrD,OAAO,CAAC,OAAO,CAAC;IANlB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;gBAGU,aAAa,EAAE,aAAa,EAG5D,OAAO,CAAC,EAAE,mBAAmB,YAAA;IAKvC,YAAY,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;IAIrC,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAIjC,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI;IAI5C,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI;IAI7C,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,KAAK,GAAG,OAAO,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI;IAI9D,IAAI,C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,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,GAAG,IAAI;IAI3C,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,GAAG,IAAI;CAG9C"}
@@ -15,11 +15,8 @@ let LoggerService = class LoggerService {
15
15
  this.options = options;
16
16
  this.logger = new logger_class_1.Logger(this.configService.getConfig(), this.options);
17
17
  }
18
- setSessionId(sessionId) {
19
- this.logger.setSessionId(sessionId);
20
- }
21
- setQuoteId(quoteId) {
22
- this.logger.setQuoteId(quoteId);
18
+ setContext(key, value) {
19
+ this.logger.setContext(key, value);
23
20
  }
24
21
  log(message, payload) {
25
22
  this.logger.log(message, payload);
@@ -27,17 +24,17 @@ let LoggerService = class LoggerService {
27
24
  info(message, payload) {
28
25
  this.logger.info(message, payload);
29
26
  }
30
- error(message, trace) {
31
- this.logger.error(message, trace ?? '');
27
+ error(message, traceOrErrorOrPayload, traceOrRemoteAddress, remoteAddress) {
28
+ this.logger.error(message, traceOrErrorOrPayload, traceOrRemoteAddress, remoteAddress);
32
29
  }
33
30
  warn(message, payload) {
34
31
  this.logger.warn(message, payload);
35
32
  }
36
- debug(message) {
37
- this.logger.debug(message);
33
+ debug(message, payload) {
34
+ this.logger.debug(message, payload);
38
35
  }
39
- verbose(message) {
40
- this.logger.verbose(message);
36
+ verbose(message, payload) {
37
+ this.logger.verbose(message, payload);
41
38
  }
42
39
  };
43
40
  exports.LoggerService = LoggerService;
@@ -0,0 +1,7 @@
1
+ import { NestMiddleware } from '@nestjs/common';
2
+ import { Request, Response, NextFunction } from 'express';
3
+ export declare class LoggerContextMiddleware implements NestMiddleware {
4
+ private generateId;
5
+ use(req: Request, _res: Response, next: NextFunction): void;
6
+ }
7
+ //# sourceMappingURL=logger-context.middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger-context.middleware.d.ts","sourceRoot":"","sources":["../../../src/middleware/logger-context.middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAI1D,qBACa,uBAAwB,YAAW,cAAc;IAC5D,OAAO,CAAC,UAAU;IAKlB,GAAG,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY;CAarD"}
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LoggerContextMiddleware = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const common_1 = require("@nestjs/common");
6
+ const crypto_1 = require("crypto");
7
+ const async_context_1 = require("../context/async-context");
8
+ let LoggerContextMiddleware = class LoggerContextMiddleware {
9
+ generateId() {
10
+ const appName = process.env.APP_TITLE?.replace(/\s+/g, '-').toLowerCase();
11
+ return appName ? `${appName}-${(0, crypto_1.randomUUID)()}` : (0, crypto_1.randomUUID)();
12
+ }
13
+ use(req, _res, next) {
14
+ const context = {
15
+ sessionId: req.headers['x-session-id'],
16
+ quoteId: req.headers['x-quote-id'],
17
+ traceId: req.headers['x-trace-id'],
18
+ correlationId: req.headers['x-correlation-id'] || this.generateId(),
19
+ userId: req.user?.id,
20
+ };
21
+ async_context_1.loggerAsyncStorage.run(context, () => {
22
+ next();
23
+ });
24
+ }
25
+ };
26
+ exports.LoggerContextMiddleware = LoggerContextMiddleware;
27
+ exports.LoggerContextMiddleware = LoggerContextMiddleware = tslib_1.__decorate([
28
+ (0, common_1.Injectable)()
29
+ ], LoggerContextMiddleware);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@edirect/logger",
3
- "version": "11.0.55",
3
+ "version": "11.0.57",
4
4
  "packageScope": "@edirect",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
@@ -17,11 +17,11 @@
17
17
  "dist"
18
18
  ],
19
19
  "dependencies": {
20
- "@nestjs/common": "^11.1.17",
20
+ "@nestjs/common": "^11.1.19",
21
21
  "pino": "10.3.1",
22
22
  "supertest": "7.2.2",
23
23
  "tslib": "^2.8.1",
24
- "@edirect/config": "11.0.55"
24
+ "@edirect/config": "11.0.57"
25
25
  },
26
26
  "nx": {
27
27
  "name": "@edirect/logger",