Skip to content

Commit

Permalink
chaynHQ#532 Added session and request logging to each logger message …
Browse files Browse the repository at this point in the history
…using cls
  • Loading branch information
leoseg committed Dec 29, 2024
1 parent 56f21a2 commit fce8469
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 8 deletions.
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ services:
context: .
dockerfile: Dockerfile
environment:
DATABASE_URL: postgres://postgres:postgres@host.docker.internal:35000/bloom
DATABASE_URL: postgres://postgres:postgres@db:5432/bloom
ports:
- 35001:35001
depends_on:
Expand Down
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"firebase": "^10.10.0",
"firebase-admin": "^12.2.0",
"lodash": "^4.17.21",
"nestjs-cls": "^4.4.1",
"newrelic": "^12.5.1",
"pg": "^8.11.5",
"pg-connection-string": "^2.6.4",
Expand All @@ -55,14 +56,15 @@
"rollbar": "^2.26.4",
"rxjs": "^7.8.1",
"storyblok-js-client": "^6.9.2",
"typeorm": "^0.3.20"
"typeorm": "^0.3.20",
"uuid": "^11.0.3"
},
"devDependencies": {
"@eslint/js": "^9.11.1",
"@golevelup/ts-jest": "^0.5.0",
"@nestjs/cli": "^10.3.2",
"@nestjs/testing": "^10.4.6",
"@nestjs/schematics": "^10.2.3",
"@nestjs/testing": "^10.4.6",
"@types/date-fns": "^2.6.0",
"@types/express": "^5.0.0",
"@types/jest": "^29.5.13",
Expand Down
11 changes: 11 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,22 @@ import { SessionModule } from './session/session.module';
import { SubscriptionUserModule } from './subscription-user/subscription-user.module';
import { UserModule } from './user/user.module';
import { WebhooksModule } from './webhooks/webhooks.module';
import { ClsModule } from 'nestjs-cls';
import { v4 as uuidv4 } from 'uuid';

@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRoot(dataSourceOptions as TypeOrmModuleOptions),
ClsModule.forRoot({
global: true,
middleware: {
mount: true,
generateId: true,
idGenerator: (req: Request) =>
req.headers['X-Request-Id'] ?? uuidv4(),
}
}),
LoggerModule,
PartnerAccessModule,
AuthModule,
Expand Down
14 changes: 13 additions & 1 deletion src/firebase/firebase-auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ import {
UnauthorizedException,
} from '@nestjs/common';
import { Request } from 'express';

import { AUTH_GUARD_ERRORS, FIREBASE_ERRORS } from 'src/utils/errors';
import { AuthService } from '../auth/auth.service';
import { UserService } from '../user/user.service';
import { IFirebaseUser } from './firebase-user.interface';
import { ClsService } from 'nestjs-cls';
import { DecodedIdToken } from 'firebase-admin/lib/auth/token-verifier';
import * as crypto from 'crypto';

@Injectable()
export class FirebaseAuthGuard implements CanActivate {
Expand All @@ -21,6 +23,7 @@ export class FirebaseAuthGuard implements CanActivate {
constructor(
private authService: AuthService,
private userService: UserService,
private cls : ClsService,
) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
Expand Down Expand Up @@ -84,6 +87,15 @@ export class FirebaseAuthGuard implements CanActivate {
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
this.setSessionId(user);
return true;
}


private setSessionId(user : DecodedIdToken) {
const uid = user.uid;
const authTime = user.auth_time;
const sessionId: string = crypto.createHash('sha256').update(`${uid}-${authTime}`).digest('hex');
this.cls.set('sessionId', sessionId);
}
}
21 changes: 17 additions & 4 deletions src/logger/logger.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,36 @@
import { ConsoleLogger } from '@nestjs/common';
import { ConsoleLogger, Inject } from '@nestjs/common';
import Rollbar from 'rollbar';
import { FIREBASE_ERRORS } from 'src/utils/errors';
import { isProduction, rollbarEnv, rollbarToken } from '../utils/constants';
import { ErrorLog } from './utils';
import { ClsService } from 'nestjs-cls';


export class Logger extends ConsoleLogger {
private rollbar?: Rollbar;

@Inject
(ClsService) private readonly cls: ClsService;

constructor(context?: string, isTimestampEnabled?) {
super(context, isTimestampEnabled);

this.initialiseRollbar();
}

log(message: string): void {
const requestId = this.cls.getId();
const decoratedMessage = `[Request ID: ${requestId}] ${message}`;
super.log(decoratedMessage);
}

error(message: string | ErrorLog, trace?: string): void {
const requestId = this.cls.getId();
const sessionId = this.cls.get('sessionId');
const decoratedMessage = `[Request ID: ${requestId}, Session ID: ${sessionId}] ${message}`;
if (this.rollbar) {
this.rollbar.error(message);
this.rollbar.error(decoratedMessage);
}
const formattedMessage = typeof message === 'string' ? message : JSON.stringify(message);
const formattedMessage = typeof decoratedMessage === 'string' ? decoratedMessage : JSON.stringify(message);

const taggedMessage = `[error] ${formattedMessage}`;
super.error(taggedMessage, trace);
Expand Down

0 comments on commit fce8469

Please sign in to comment.