logs setup

This commit is contained in:
AdisakKanthawilang 2024-08-09 10:17:39 +07:00
parent 22af14721d
commit 8d087d3a3b
4 changed files with 203 additions and 0 deletions

View file

@ -5,6 +5,7 @@ import { Position } from "../entities/Position";
import { EmployeePosMaster } from "../entities/EmployeePosMaster";
import { EmployeePosition } from "../entities/EmployeePosition";
import { In } from "typeorm";
import { RequestWithUser } from "../middlewares/user";
export function calculateAge(start: Date, end = new Date()) {
if (start.getTime() > end.getTime()) return null;
@ -172,3 +173,39 @@ export async function removeProfileInOrganize(profileId: string, type:string) {
.execute();
}
}
//logs
export type DataDiff = {
before: any;
after: any;
};
export type LogSequence = {
action: string;
status: "success" | "error";
description: string;
query?: any;
request?: {
method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
url?: string;
payload?: string;
response?: string;
};
};
export function setLogDataDiff(req: RequestWithUser, data: DataDiff) {
req.app.locals.logData.dataDiff = {
before: JSON.stringify(data.before),
after: JSON.stringify(data.after),
};
}
export function addLogSequence(req: RequestWithUser, data: LogSequence) {
if (!req?.app?.locals?.logData?.sequence) {
req.app.locals.logData.sequence = [];
}
req.app.locals.logData.sequence = req.app.locals.logData.sequence.concat(data);
}
export function editLogSequence(req: RequestWithUser, index: number, data: LogSequence) {
req.app.locals.logData.sequence[index] = data;
}

80
src/middlewares/logs.ts Normal file
View file

@ -0,0 +1,80 @@
import { NextFunction, Request, Response } from "express";
import { Client } from "@elastic/elasticsearch";
if (!process.env.ELASTICSEARCH_INDEX) {
throw new Error("Require ELASTICSEARCH_INDEX to store log.");
}
const ELASTICSEARCH_INDEX = process.env.ELASTICSEARCH_INDEX;
const LOG_LEVEL_MAP: Record<string, number> = {
debug: 4,
info: 3,
warning: 2,
error: 1,
none: 0,
};
const elasticsearch = new Client({
node: `${process.env.ELASTICSEARCH_PROTOCOL}://${process.env.ELASTICSEARCH_HOST}:${process.env.ELASTICSEARCH_PORT}`,
});
async function logMiddleware(req: Request, res: Response, next: NextFunction) {
if (!req.url.startsWith("/api/")) return next();
let data: any;
const originalJson = res.json;
res.json = function (v: any) {
data = v;
return originalJson.call(this, v);
};
const timestamp = new Date().toISOString();
const start = performance.now();
req.app.locals.logData = {};
res.on("finish", () => {
if (!req.url.startsWith("/api/")) return;
let system = "org";
if (req.url.startsWith("/api/v1/org/metadata/")) system="metadata";
if (req.url.startsWith("/api/v1/org/auth/authRoleAttr/")) system = "admin";
if (req.url.startsWith("/api/v1/org/auth/authRoleAttr/")) system = "admin";
if (req.url.startsWith("/api/v1/org/auth/authRoleAttr/")) system = "admin";
if (req.url.startsWith("/api/v1/org/auth/authRoleAttr/")) system = "admin";
const level = LOG_LEVEL_MAP[process.env.LOG_LEVEL ?? "debug"] || 4;
if (level === 1 && res.statusCode < 500) return;
if (level === 2 && res.statusCode < 400) return;
if (level === 3 && res.statusCode < 200) return;
const obj = {
logType: res.statusCode >= 500 ? "error" : res.statusCode >= 400 ? "warning" : "info",
ip: req.ip,
systemName: system,
startTimeStamp: timestamp,
endTimeStamp: new Date().toISOString(),
processTime: performance.now() - start,
host: req.hostname,
method: req.method,
endpoint: req.url,
responseCode: String(res.statusCode === 304 ? 200 : res.statusCode),
responseDescription: data?.message,
input: (level === 4 && JSON.stringify(req.body, null, 2)) || undefined,
output: (level === 4 && JSON.stringify(data, null, 2)) || undefined,
...req.app.locals.logData,
};
elasticsearch.index({
index: ELASTICSEARCH_INDEX,
document: obj,
});
});
return next();
}
export default logMiddleware;