Skip to content

Logging: Add request id to the app logs for easy log tracking #68

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"jsonwebtoken": "^9.0.2",
"jwks-rsa": "^3.2.0",
"lodash": "^4.17.21",
"nanoid": "^5.1.5",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"trolleyhq": "^1.1.0",
Expand Down
26 changes: 26 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions src/api/api.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { HealthCheckController } from './health-check/healthCheck.controller';
import { GlobalProvidersModule } from 'src/shared/global/globalProviders.module';
import { APP_GUARD } from '@nestjs/core';
import { TokenValidatorMiddleware } from 'src/core/auth/middleware/tokenValidator.middleware';
import { CreateRequestStoreMiddleware } from 'src/core/request/createRequestStore.middleware';
import { AuthGuard, RolesGuard } from 'src/core/auth/guards';
import { TopcoderModule } from 'src/shared/topcoder/topcoder.module';
import { OriginRepository } from './repository/origin.repo';
Expand Down Expand Up @@ -48,5 +49,6 @@ import { WithdrawalModule } from './withdrawal/withdrawal.module';
export class ApiModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(TokenValidatorMiddleware).forRoutes('*');
consumer.apply(CreateRequestStoreMiddleware).forRoutes('*');
}
}
14 changes: 14 additions & 0 deletions src/core/request/createRequestStore.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Response, NextFunction } from 'express';
import { RequestMetadata, saveStore } from './requestStore';

@Injectable()
export class CreateRequestStoreMiddleware implements NestMiddleware {
constructor() {}

use(req: any, res: Response, next: NextFunction) {
const requestMetaData = new RequestMetadata({});

saveStore(requestMetaData, next);
}
}
39 changes: 39 additions & 0 deletions src/core/request/requestStore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { AsyncLocalStorage } from 'async_hooks';
import { NextFunction } from 'express';
import { nanoid } from 'nanoid';

// Class for storing request specific metadata
export class RequestMetadata {
requestId: string;

// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-object-type
constructor(params: { requestId?: string }) {
this.requestId = params.requestId ?? nanoid(11);
}
}

// Create a AsyncLocalStorage of type RequestMetaData for storing request specific data
const asyncStorage = new AsyncLocalStorage<RequestMetadata>();

// Gets the RequestMetadada object associated with the current request
export function getStore(): RequestMetadata {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high
correctness
The getStore function returns a RequestMetadata object with an empty requestId if the store is undefined. This could lead to logs with missing request IDs, which may defeat the purpose of tracking requests. Consider initializing with a new nanoid instead.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is happening only for "root"-level logging - and is expected - they are not part of any request.

let store = asyncStorage.getStore();
if (store === undefined) {
store = new RequestMetadata({
requestId: '',
});
}

return store;
}

// For use in middleware
// Saves RequestMetadata for the current request
export function saveStore(
requestMetaData: RequestMetadata,
next: NextFunction,
) {
asyncStorage.run(requestMetaData, () => {
next();
});
}
10 changes: 9 additions & 1 deletion src/shared/global/logger.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { Logger as NestLogger } from '@nestjs/common';
import stringify from 'json-stringify-safe';
import { getStore } from 'src/core/request/requestStore';

export class Logger extends NestLogger {
private get store() {
return getStore();
}

log(...messages: any[]): void {
super.log(this.formatMessages(messages));
}
Expand All @@ -19,7 +24,10 @@ export class Logger extends NestLogger {
}

private formatMessages(messages: any[]): string {
return messages
const requestIdPrefix = this.store.requestId
? [`{${this.store.requestId}}`]
: [];
return [...requestIdPrefix, ...messages]
.map((msg) =>
typeof msg === 'object' ? stringify(msg, null, 2) : String(msg),
)
Expand Down