79 lines
2.1 KiB
TypeScript
79 lines
2.1 KiB
TypeScript
import { NextFunction, Request, Response } from "express";
|
|
import elasticsearch from "../services/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,
|
|
};
|
|
|
|
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().toString();
|
|
const start = performance.now();
|
|
|
|
req.app.locals.logData = {};
|
|
|
|
res.on("finish", () => {
|
|
if (!req.url.startsWith("/api/")) return;
|
|
|
|
const level = LOG_LEVEL_MAP[process.env.LOG_LEVEL ?? "info"] || 1;
|
|
|
|
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",
|
|
systemName: "JWS-SOS",
|
|
startTimeStamp: timestamp,
|
|
endTimeStamp: new Date().toString(),
|
|
processTime: performance.now() - start,
|
|
host: req.hostname,
|
|
sessionId: req.headers["x-session-id"],
|
|
rtId: req.headers["x-rtid"],
|
|
tId: req.headers["x-tid"],
|
|
method: req.method,
|
|
endpoint: req.url,
|
|
responseCode: res.statusCode,
|
|
responseDescription:
|
|
data?.devMessage !== undefined
|
|
? data.devMessage
|
|
: { 200: "success", 201: "created_success", 204: "no_content", 304: "success" }[
|
|
res.statusCode
|
|
],
|
|
input: (level === 4 && JSON.stringify(req.body, null, 2)) || undefined,
|
|
output: (level === 4 && JSON.stringify(data, null, 2)) || undefined,
|
|
...req.app.locals.logData,
|
|
};
|
|
|
|
console.log(obj);
|
|
|
|
elasticsearch.index({
|
|
index: ELASTICSEARCH_INDEX,
|
|
document: obj,
|
|
});
|
|
});
|
|
|
|
return next();
|
|
}
|
|
|
|
export default logMiddleware;
|