Tiếp tục với series, tới giờ lỗi của TaskFlow vẫn in bằng console.error (Bài 10) và mã X-Request-Id ở Bài 11 chưa có trong log. Bài này mình sẽ giới thiệu với mọi người về logging và serialization trong NestJS.
1. Logger có sẵn trong NestJS.
Class Logger của @nestjs/common là logger in các dòng lúc khởi động. Mỗi class tạo một logger với context là tên class:
- src/auth/auth.service.ts (đoạn trích; import thêm Logger từ @nestjs/common)
export class AuthService {
private readonly logger = new Logger(AuthService.name);
// ...
if (!user || !valid) {
// Ghi email để lần theo kiểu dò mật khẩu, không bao giờ ghi mật khẩu
this.logger.warn('Đăng nhập thất bại', { email: dto.email });
throw new UnauthorizedException('Email hoặc mật khẩu không đúng');
}
Đăng nhập sai mật khẩu, terminal chạy ứng dụng in ra:
[Nest] 117 - 11/15/2026, 10:47:44 AM WARN [AuthService] Đăng nhập thất bại { email: '[email protected]' }
Trong đó:
- Các level gồm
fatal,error,warn,log,debug,verbose. Muốn chỉ in từwarntrở lên thì truyềnlogger: filterLogLevels('>=warn')vàoNestFactory.create(). - Object truyền sau message là dữ liệu đi kèm của cùng dòng log (structured logging, đã giới thiệu ở Bài 1).
Mình cũng thay console.error trong AllExceptionsFilter và ActivitiesService bằng this.logger.error('Lỗi không mong muốn', exception).
2. Structured logging với log JSON.
Ở production, log nên là JSON mỗi dòng một bản ghi để hệ thống quản lý log (Loki, CloudWatch...) lọc theo field. Thử bật json của ConsoleLogger:
- src/main.ts (đoạn trích, chỉ để thử; import thêm ConsoleLogger)
const app = await NestFactory.create(AppModule, {
// ...
logger: new ConsoleLogger({ json: true }),
});
{"level":"warn","pid":93,"timestamp":1794739628931,"message":"Đăng nhập thất bại","context":"AuthService","params":{"email":"[email protected]"}}
Dữ liệu đi kèm nằm trong params. Còn thiếu một thứ: dòng log này thuộc request nào? ConsoleLogger không biết request, nên mình chuyển sang pino.
3. Custom logger với pino.
Pino là logger JSON rất nhanh của Node.js. Package nestjs-pino (5.3.1) dùng pino-http ghi log mỗi request và dùng AsyncLocalStorage gắn thông tin request vào mọi dòng log ghi trong request đó, kể cả log từ service:
npm install nestjs-pino pino-http pino
- src/app.module.ts (đoạn trích trong imports, ngay sau ConfigModule; import LoggerModule, nativeLoggerOptions từ nestjs-pino)
LoggerModule.forRoot({
pinoHttp: {
// Cùng dạng JSON với ConsoleLogger: level, message, context, params
...nativeLoggerOptions,
// Dùng X-Request-Id mà middleware requestId (Bài 11) đã gắn vào response
genReqId: (_req, res) => String(res.getHeader('X-Request-Id')),
customAttributeKeys: { reqId: 'requestId' },
// Log ghi trong request chỉ kèm requestId, không kèm cả req
quietReqLogger: true,
// Thay giá trị bằng "[Redacted]" trước khi ghi
redact: [
'req.headers.authorization',
'req.headers.cookie',
'res.headers["set-cookie"]',
'password',
'*.password',
'*.*.password',
],
},
}),
Trong đó:
requestIdlà chính mã client nhận ở headerX-Request-Id: có mã này là tìm ra mọi dòng log của request đó. MiddlewarerequestIdđăng ký bằngapp.use()nên chạy trướcpino-http.redactche headerAuthorization, cookie và fieldpasswordở tối đa ba cấp (VDparams.dto.password).
- src/main.ts (đoạn trích; import NativeLogger từ nestjs-pino)
const app = await NestFactory.create(AppModule, {
// ...
bufferLogs: true, // giữ log khởi động tới khi có logger pino
});
app.useLogger(app.get(NativeLogger));
app.enableShutdownHooks();
// /graphql vốn không có prefix, exclude để middleware pino-http chạy cả cho /graphql
app.setGlobalPrefix('api', { exclude: ['graphql'] });
NativeLogger nhận tham số như ConsoleLogger nên các lời gọi this.logger.warn(...) giữ nguyên. pino-http đã tự ghi log mỗi request nên mình xoá LoggerMiddleware của Bài 11 cùng method configure() trong AppModule. Thử đăng nhập sai:
curl -i http://localhost:3000/api/v1/auth/login -H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"sai-mat-khau"}'
# HTTP/1.1 401 Unauthorized
# X-Request-Id: 607372db-de67-4de7-b75c-5307bd903e4d
# ...
# Log của ứng dụng (mỗi bản ghi một dòng, mình rút gọn bằng ...):
# {"level":"warn",...,"requestId":"607372db-de67-4de7-b75c-5307bd903e4d","context":"AuthService","params":{"email":"[email protected]"},"message":"Đăng nhập thất bại"}
# {"level":"log",...,"requestId":"607372db-de67-4de7-b75c-5307bd903e4d","req":{...,"method":"POST","url":"/api/v1/auth/login",...},"res":{"statusCode":401,...},"responseTime":241,"message":"request completed"}
Gọi route cần token ($A như các bài trước), header bị che trong log:
curl http://localhost:3000/api/v1/auth/me -H "$A"
# Log: ..."url":"/api/v1/auth/me",...,"headers":{...,"authorization":"[Redacted]"},...
4. Ẩn field nhạy cảm khi trả response.
Hiện TaskFlow giấu password bằng select (Bài 20) và storedName bằng attachmentSelect (Bài 22): chỉ cần một query quên select là lộ. Serialization lọc dữ liệu ở một chỗ, ngay trước khi gửi cho client.
Cách quen thuộc là ClassSerializerInterceptor với @Exclude() của class-transformer, nhưng handler phải trả về instance của class, trong khi Prisma trả object thường. NestJS 12 có StandardSchemaSerializerInterceptor: response đi qua một schema Zod, mà z.object() bỏ mọi field không khai báo, nên schema là một allow-list:
- src/auth/user-response.schema.ts
import { z } from 'zod';
import { Role } from '../generated/prisma/enums.js';
// Allow-list: chỉ các field này được trả cho client, field khác (password...) bị bỏ
export const userResponseSchema = z.object({
id: z.number(),
name: z.string(),
email: z.string(),
role: z.enum(Role),
});
Đăng ký interceptor toàn cục, sau TransformInterceptor (Bài 13) để nó lọc kết quả của handler trước khi được bọc { data }:
- src/app.module.ts (đoạn trích trong providers; import StandardSchemaSerializerInterceptor từ @nestjs/common)
{ provide: APP_INTERCEPTOR, useClass: TransformInterceptor },
// Đăng ký sau nên chạy trong TransformInterceptor: lọc kết quả trước khi bọc { data }
{
provide: APP_INTERCEPTOR,
useClass: StandardSchemaSerializerInterceptor,
},
Route nào cần lọc thì chọn schema bằng @SerializeOptions():
- src/auth/auth.controller.ts (đoạn trích; import SerializeOptions, userResponseSchema; me() gắn tương tự)
@Public()
@Post('register')
@SerializeOptions({ schema: userResponseSchema })
register(@Body() dto: RegisterDto): Promise<AuthUser> {
return this.authService.register(dto);
}
Trong đó:
- Handler trả mảng thì schema áp dụng cho từng phần tử. Handler không có schema,
nullvàStreamableFileđi qua nguyên vẹn. - Response không khớp schema (thiếu field, sai kiểu) là lỗi của server: client nhận
500, log ghiSerialization failed: .... AttachmentsControllergắn@SerializeOptions({ schema: attachmentResponseSchema })ở cấp class (schema không cóstoredName).
Mình thử xoá select trong AuthService.register() để service trả cả bản ghi, response vẫn không có password (thử xong nhớ khôi phục):
curl http://localhost:3000/api/v1/auth/register -H "Content-Type: application/json" \
-d '{"name":"An","email":"[email protected]","password":"matkhau123"}'
# {"data":{"id":2,"name":"An","email":"[email protected]","role":"user"}}
Lưu ý: Bài này cũng sửa hai chỗ nhỏ. Thứ nhất, NODE_ENV trong envSchema (src/config/env.validation.ts) đổi thành .default('production'): quên đặt thì /docs, GraphiQL tắt (.env.example vẫn đặt development).
Thứ hai, WebSocket /graphql từ chối query/mutation bằng lỗi rõ ràng thay vì lỗi 500, qua onSubscribe của graphql-ws:
- src/common/graphql/only-subscriptions.ts
import { GraphQLError, getOperationAST, parse } from 'graphql';
import type { SubscribePayload } from 'graphql-ws';
// graphql-ws onSubscribe: WebSocket chỉ nhận subscription, query/mutation đi qua HTTP
export function onlySubscriptions(
_ctx: unknown,
_id: string,
payload: SubscribePayload,
): readonly GraphQLError[] | void {
let operation: string | undefined;
try {
operation = getOperationAST(
parse(payload.query),
payload.operationName,
)?.operation;
} catch (error) {
// Lỗi cú pháp: báo lại cho client như lỗi GraphQL bình thường
return [error as GraphQLError];
}
if (operation !== 'subscription') {
return [
new GraphQLError(
'Chỉ hỗ trợ subscription qua WebSocket, query/mutation hãy gửi qua HTTP',
),
];
}
}
Trong GraphQLModule (src/app.module.ts) đổi thành subscriptions: { 'graphql-ws': { onSubscribe: onlySubscriptions } }.
5. Lời kết.
Như vậy mình đã giới thiệu xong về logging và serialization trong NestJS: Logger, log JSON, pino với requestId và redact, cùng StandardSchemaSerializerInterceptor. Bài sau mình sẽ giới thiệu về cache trong NestJS.
Đăng ký nhận tin.
Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!





0 Comments