-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #63 from krystxf/refactor/be-logging
refactor(be): request logging
- Loading branch information
Showing
14 changed files
with
192 additions
and
39 deletions.
There are no files selected for viewing
13 changes: 13 additions & 0 deletions
13
apps/backend/prisma/migrations/20241205005919_request_logs/migration.sql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
-- CreateTable | ||
CREATE TABLE "RequestLog" ( | ||
"id" BIGSERIAL NOT NULL, | ||
"method" TEXT NOT NULL, | ||
"path" TEXT NOT NULL, | ||
"status" INTEGER NOT NULL, | ||
"duration" INTEGER NOT NULL, | ||
"response" TEXT, | ||
"userAgent" TEXT, | ||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, | ||
|
||
CONSTRAINT "RequestLog_pkey" PRIMARY KEY ("id") | ||
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import { Injectable, NestMiddleware } from "@nestjs/common"; | ||
import { NextFunction, Request, Response } from "express"; | ||
|
||
import { PrismaService } from "src/modules/prisma/prisma.service"; | ||
|
||
@Injectable() | ||
export class RequestLoggerMiddleware implements NestMiddleware { | ||
constructor(private readonly prisma: PrismaService) {} | ||
|
||
async use(req: Request, res: Response, next: NextFunction) { | ||
const start = Date.now(); | ||
|
||
// Intercept the response to capture the body | ||
const originalSend = res.send; | ||
let responseBody: unknown; | ||
|
||
res.send = (body): Response => { | ||
responseBody = body; // Capture the response body | ||
return originalSend.call(res, body); // Call the original `send` method | ||
}; | ||
|
||
// Attach an event listener to log after the response is sent | ||
res.on("finish", async () => { | ||
const duration = Date.now() - start; | ||
const { | ||
method, | ||
url: path, | ||
headers: { "user-agent": userAgent = null }, | ||
} = req; | ||
const { statusCode } = res; | ||
const responseString = | ||
typeof responseBody === "string" | ||
? responseBody | ||
: JSON.stringify(responseBody); | ||
|
||
const ignoreResponse = ["/v1/stop/all", "/v1/platform/"].some( | ||
(item) => path.startsWith(item), | ||
); | ||
|
||
if (path.startsWith("/status")) { | ||
return; | ||
} | ||
|
||
try { | ||
// Log the request details to the database | ||
await this.prisma.requestLog.create({ | ||
data: { | ||
method, | ||
path, | ||
status: statusCode, | ||
duration, | ||
userAgent, | ||
response: ignoreResponse ? null : responseString, | ||
}, | ||
}); | ||
} catch (error) { | ||
console.error("Failed to log request:", error); | ||
} | ||
}); | ||
|
||
next(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
18 changes: 18 additions & 0 deletions
18
apps/backend/src/modules/logs-cleanup/logs-cleanup.controller.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import { Controller, OnModuleInit } from "@nestjs/common"; | ||
import { Cron, CronExpression } from "@nestjs/schedule"; | ||
|
||
import { LogsCleanupService } from "src/modules/logs-cleanup/logs-cleanup.service"; | ||
|
||
@Controller("logs-cleanup") | ||
export class LogsCleanupController implements OnModuleInit { | ||
constructor(private readonly logsCleanupService: LogsCleanupService) {} | ||
|
||
async onModuleInit(): Promise<void> { | ||
return this.logsCleanupService.cleanupLogs(); | ||
} | ||
|
||
@Cron(CronExpression.EVERY_10_MINUTES) | ||
async cronLogsCleanup(): Promise<void> { | ||
return this.logsCleanupService.cleanupLogs(); | ||
} | ||
} |
11 changes: 11 additions & 0 deletions
11
apps/backend/src/modules/logs-cleanup/logs-cleanup.module.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import { Module } from "@nestjs/common"; | ||
|
||
import { LogsCleanupController } from "src/modules/logs-cleanup/logs-cleanup.controller"; | ||
import { LogsCleanupService } from "src/modules/logs-cleanup/logs-cleanup.service"; | ||
|
||
@Module({ | ||
controllers: [LogsCleanupController], | ||
providers: [LogsCleanupService], | ||
imports: [], | ||
}) | ||
export class LogsCleanupModule {} |
60 changes: 60 additions & 0 deletions
60
apps/backend/src/modules/logs-cleanup/logs-cleanup.service.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
import { Injectable } from "@nestjs/common"; | ||
|
||
import { LogLevel, LogMessage } from "src/enums/log.enum"; | ||
import { LoggerService } from "src/modules/logger/logger.service"; | ||
import { PrismaService } from "src/modules/prisma/prisma.service"; | ||
|
||
const MAX_COUNT = 500_000; | ||
|
||
@Injectable() | ||
export class LogsCleanupService { | ||
constructor( | ||
private readonly prisma: PrismaService, | ||
private readonly logger: LoggerService, | ||
) {} | ||
|
||
async cleanupLogs(): Promise<void> { | ||
try { | ||
const recordCount = await this.prisma.requestLog.count(); | ||
|
||
if (recordCount < MAX_COUNT) { | ||
return; | ||
} | ||
|
||
const last = await this.prisma.requestLog.findFirst({ | ||
orderBy: { createdAt: "desc" }, | ||
skip: MAX_COUNT, | ||
}); | ||
|
||
if (!last) { | ||
return; | ||
} | ||
|
||
const { count } = await this.prisma.requestLog.deleteMany({ | ||
where: { | ||
createdAt: { | ||
lte: last.createdAt, | ||
}, | ||
}, | ||
}); | ||
|
||
await this.logger.createLog( | ||
LogLevel.log, | ||
LogMessage.REQUEST_LOGS_CLEANUP, | ||
{ | ||
message: "Successfully removed old logs", | ||
count, | ||
}, | ||
); | ||
} catch (error) { | ||
await this.logger.createLog( | ||
LogLevel.error, | ||
LogMessage.REQUEST_LOGS_CLEANUP, | ||
{ | ||
message: "Failed to cleanup logs", | ||
error: JSON.stringify(error), | ||
}, | ||
); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
31617b1
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Successfully deployed to the following URLs:
metro-now – ./
metro-now-git-main-krystofs-projects-e2322253.vercel.app
metro-now-krystofs-projects-e2322253.vercel.app
metronow.vercel.app