feat: add logging
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
import { Injectable, OnApplicationShutdown } from '@nestjs/common';
|
||||
import { PinoLogger } from 'nestjs-pino';
|
||||
import { RequestContextService } from './request-context.service';
|
||||
|
||||
type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
||||
type LogContext = Record<string, string | number | boolean | undefined>;
|
||||
|
||||
const allowedFields = new Set([
|
||||
'service',
|
||||
'environment',
|
||||
'requestId',
|
||||
'clientRequestId',
|
||||
'userId',
|
||||
'brokerageAccountId',
|
||||
'method',
|
||||
'route',
|
||||
'status',
|
||||
'durationMs',
|
||||
'code',
|
||||
'stack',
|
||||
'operation',
|
||||
'grpcCode',
|
||||
'attempts',
|
||||
'count',
|
||||
'found',
|
||||
]);
|
||||
|
||||
@Injectable()
|
||||
export class StructuredLogger implements OnApplicationShutdown {
|
||||
constructor(
|
||||
private readonly requestContext: RequestContextService,
|
||||
private readonly pino: PinoLogger,
|
||||
) {}
|
||||
|
||||
info(message: string, context?: LogContext): void {
|
||||
this.write('info', message, context);
|
||||
}
|
||||
|
||||
event(level: LogLevel, message: string, context?: LogContext): void {
|
||||
this.write(level, message, context);
|
||||
}
|
||||
|
||||
onApplicationShutdown(): void {
|
||||
this.info('application.stopped');
|
||||
}
|
||||
|
||||
private write(
|
||||
level: LogLevel,
|
||||
message: string,
|
||||
context: LogContext = {},
|
||||
): void {
|
||||
this.pino[level](
|
||||
this.safeContext({ ...this.requestContext.get(), ...context }),
|
||||
message,
|
||||
);
|
||||
}
|
||||
|
||||
private safeContext(context: LogContext): LogContext {
|
||||
return Object.fromEntries(
|
||||
Object.entries(context).filter(
|
||||
([key, value]) => allowedFields.has(key) && value !== undefined,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user