feat: add log middleware
This commit is contained in:
parent
1f7b4a24e6
commit
41c4d5e8f2
1 changed files with 62 additions and 0 deletions
62
src/middlewares/log.ts
Normal file
62
src/middlewares/log.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
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", () => {
|
||||||
|
const obj = {
|
||||||
|
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: req.body,
|
||||||
|
output: data,
|
||||||
|
...req.app.locals.logData,
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log(obj);
|
||||||
|
|
||||||
|
elasticsearch.index({
|
||||||
|
index: ELASTICSEARCH_INDEX,
|
||||||
|
document: obj,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
export default logMiddleware;
|
||||||
Loading…
Add table
Add a link
Reference in a new issue