feat: add logging
This commit is contained in:
@@ -6,10 +6,11 @@ describe('HttpExceptionFilter', () => {
|
||||
const status = jest.fn().mockReturnThis();
|
||||
const type = jest.fn().mockReturnThis();
|
||||
const json = jest.fn();
|
||||
const locals: Record<string, unknown> = {};
|
||||
const filter = new HttpExceptionFilter();
|
||||
const host = {
|
||||
switchToHttp: () => ({
|
||||
getResponse: () => ({ status, type, json }),
|
||||
getResponse: () => ({ status, type, json, locals }),
|
||||
}),
|
||||
} as unknown as ArgumentsHost;
|
||||
|
||||
@@ -21,5 +22,8 @@ describe('HttpExceptionFilter', () => {
|
||||
status: 500,
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
});
|
||||
expect(locals.publicErrorCode).toBe('INTERNAL_SERVER_ERROR');
|
||||
expect(typeof locals.errorStack).toBe('string');
|
||||
expect(locals.errorStack).not.toContain('database password: secret');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -23,12 +23,24 @@ export class HttpExceptionFilter implements ExceptionFilter {
|
||||
const isValidation = Array.isArray(
|
||||
(payload as { message?: unknown })?.message,
|
||||
);
|
||||
const code = isValidation
|
||||
? 'VALIDATION_ERROR'
|
||||
: this.codeFor(status, payload);
|
||||
(response.locals ??= {}).publicErrorCode = code;
|
||||
if (
|
||||
status >= Number(HttpStatus.INTERNAL_SERVER_ERROR) &&
|
||||
exception instanceof Error
|
||||
)
|
||||
response.locals.errorStack = exception.stack
|
||||
?.split('\n')
|
||||
.slice(1)
|
||||
.join('\n');
|
||||
response
|
||||
.status(status)
|
||||
.type('application/problem+json')
|
||||
.json({
|
||||
status,
|
||||
code: isValidation ? 'VALIDATION_ERROR' : this.codeFor(status, payload),
|
||||
code,
|
||||
...(isValidation
|
||||
? {
|
||||
errors: this.validationErrors(
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { RequestContextService } from './request-context.service';
|
||||
import { RequestLoggingMiddleware } from './request-logging.middleware';
|
||||
import { StructuredLogger } from './structured-logger.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [
|
||||
RequestContextService,
|
||||
RequestLoggingMiddleware,
|
||||
StructuredLogger,
|
||||
],
|
||||
exports: [RequestContextService, RequestLoggingMiddleware, StructuredLogger],
|
||||
})
|
||||
export class LoggingModule {}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
|
||||
export type RequestLogContext = {
|
||||
requestId: string;
|
||||
clientRequestId?: string;
|
||||
userId?: string;
|
||||
brokerageAccountId?: string;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class RequestContextService {
|
||||
private readonly storage = new AsyncLocalStorage<RequestLogContext>();
|
||||
|
||||
run<T>(context: RequestLogContext, callback: () => T): T {
|
||||
return this.storage.run(context, callback);
|
||||
}
|
||||
|
||||
get(): RequestLogContext | undefined {
|
||||
return this.storage.getStore();
|
||||
}
|
||||
|
||||
set(context: Partial<RequestLogContext>): void {
|
||||
const current = this.storage.getStore();
|
||||
if (current) Object.assign(current, context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { RequestLoggingMiddleware } from './request-logging.middleware';
|
||||
|
||||
describe('RequestLoggingMiddleware', () => {
|
||||
it('returns a server ID and emits one safe completion event', () => {
|
||||
const requestContext = {
|
||||
run: jest.fn((_: unknown, next: () => void) => next()),
|
||||
};
|
||||
const logger = { event: jest.fn() };
|
||||
const middleware = new RequestLoggingMiddleware(
|
||||
requestContext as never,
|
||||
logger as never,
|
||||
);
|
||||
const response = Object.assign(new EventEmitter(), {
|
||||
statusCode: 200,
|
||||
locals: {},
|
||||
setHeader: jest.fn(),
|
||||
});
|
||||
const next = jest.fn();
|
||||
|
||||
const request: {
|
||||
method: string;
|
||||
baseUrl: string;
|
||||
route: { path: string };
|
||||
header: jest.Mock<string>;
|
||||
id?: string;
|
||||
} = {
|
||||
method: 'GET',
|
||||
baseUrl: '/api/v1',
|
||||
route: { path: '/accounts/:id' },
|
||||
header: jest.fn(() => 'a2dc6fbb-5a48-4c3c-9e3e-4fbf4d638a43'),
|
||||
};
|
||||
middleware.use(request as never, response as never, next);
|
||||
response.emit('finish');
|
||||
|
||||
expect(response.setHeader).toHaveBeenCalledWith(
|
||||
'X-Request-ID',
|
||||
expect.stringMatching(/^[0-9a-f-]{36}$/i),
|
||||
);
|
||||
expect(request.id).toMatch(/^[0-9a-f-]{36}$/i);
|
||||
expect(requestContext.run).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
clientRequestId: 'a2dc6fbb-5a48-4c3c-9e3e-4fbf4d638a43',
|
||||
}),
|
||||
next,
|
||||
);
|
||||
expect(logger.event).toHaveBeenCalledWith(
|
||||
'info',
|
||||
'http.request.completed',
|
||||
expect.objectContaining({ route: '/api/v1/accounts/:id', status: 200 }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Injectable, NestMiddleware } from '@nestjs/common';
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { RequestContextService } from './request-context.service';
|
||||
import { StructuredLogger } from './structured-logger.service';
|
||||
|
||||
const uuid =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
@Injectable()
|
||||
export class RequestLoggingMiddleware implements NestMiddleware {
|
||||
constructor(
|
||||
private readonly requestContext: RequestContextService,
|
||||
private readonly logger: StructuredLogger,
|
||||
) {}
|
||||
|
||||
use(request: Request, response: Response, next: NextFunction): void {
|
||||
const incoming = request.header('x-request-id');
|
||||
const clientRequestId =
|
||||
incoming && uuid.test(incoming) ? incoming : undefined;
|
||||
const existingRequestId = (request as Request & { id?: unknown }).id;
|
||||
const requestId =
|
||||
typeof existingRequestId === 'string' ? existingRequestId : randomUUID();
|
||||
(request as unknown as { id: string }).id = requestId;
|
||||
const startedAt = performance.now();
|
||||
|
||||
response.setHeader('X-Request-ID', requestId);
|
||||
response.on('finish', () => {
|
||||
const routeRequest: unknown = request;
|
||||
const routePath = (routeRequest as { route?: { path?: unknown } }).route
|
||||
?.path;
|
||||
const route =
|
||||
typeof routePath === 'string'
|
||||
? `${request.baseUrl}${routePath}`
|
||||
: '<unmatched>';
|
||||
const context = {
|
||||
method: request.method,
|
||||
route,
|
||||
status: response.statusCode,
|
||||
durationMs: Math.round(performance.now() - startedAt),
|
||||
...(response.locals.publicErrorCode
|
||||
? { code: response.locals.publicErrorCode as string }
|
||||
: {}),
|
||||
...(response.locals.errorStack
|
||||
? { stack: response.locals.errorStack as string }
|
||||
: {}),
|
||||
};
|
||||
const level =
|
||||
response.statusCode >= 500
|
||||
? 'error'
|
||||
: response.statusCode === 429 ||
|
||||
response.statusCode === 401 ||
|
||||
response.statusCode === 403
|
||||
? 'warn'
|
||||
: 'info';
|
||||
this.logger.event(level, 'http.request.completed', context);
|
||||
});
|
||||
|
||||
this.requestContext.run(
|
||||
{
|
||||
requestId,
|
||||
...(clientRequestId ? { clientRequestId } : {}),
|
||||
},
|
||||
next,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { StructuredLogger } from './structured-logger.service';
|
||||
|
||||
describe('StructuredLogger', () => {
|
||||
const context = { get: jest.fn() };
|
||||
const pino = {
|
||||
debug: jest.fn(),
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
it('passes only allowlisted fields to Pino', () => {
|
||||
context.get.mockReturnValue({ requestId: 'request', token: 'secret' });
|
||||
const logger = new StructuredLogger(context as never, pino as never);
|
||||
|
||||
logger.info('event', {
|
||||
userId: 'user',
|
||||
brokerageAccountId: 'account',
|
||||
password: 'secret',
|
||||
});
|
||||
|
||||
expect(pino.info).toHaveBeenCalledWith(
|
||||
{
|
||||
requestId: 'request',
|
||||
userId: 'user',
|
||||
brokerageAccountId: 'account',
|
||||
},
|
||||
'event',
|
||||
);
|
||||
});
|
||||
|
||||
it('delegates event levels to Pino', () => {
|
||||
context.get.mockReturnValue(undefined);
|
||||
const logger = new StructuredLogger(context as never, pino as never);
|
||||
|
||||
logger.event('debug', 'debug event');
|
||||
logger.event('warn', 'warn event');
|
||||
|
||||
expect(pino.debug).toHaveBeenCalledWith({}, 'debug event');
|
||||
expect(pino.warn).toHaveBeenCalledWith({}, 'warn event');
|
||||
});
|
||||
});
|
||||
@@ -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