UNPKG

@hoangnam.io/qa-tools

Version:

Logging, Error handling, Notifying for Express codebase

57 lines (52 loc) 1.9 kB
const { trace, context } = require("@opentelemetry/api"); const moment = require("moment-timezone"); const { LogLevel } = require("./constance"); function genLogFormatFunc(config) { const { app, appName, TZ, extractCallerFunc, sensitiveRoutes } = config; // record response body const originalSend = app.response.send; app.response.send = function sendOverride(body) { this.responseBody = Buffer.isBuffer(body) ? body.toString() : body; return originalSend.call(this, body); }; return function logFormatFunction(tokens, req, res) { const activeSpan = trace.getSpan(context.active()); const { traceId, spanId, traceFlags } = activeSpan?.spanContext() || {}; const logEntry = { severity: LogLevel.INFO, appName, logType: "RequestLog", zTimestamp: moment.tz(TZ).format(), timestamp: Date.now(), caller: extractCallerFunc(req), userAgent: req.headers["user-agent"], ip: req.ip, method: tokens.method(req, res), url: tokens.url(req, res), requestContentLength: req.headers["content-length"], responseContentLength: Number(tokens.res(req, res, "content-length")), contentLengthUnit: "bytes", responseTime: Number(tokens["response-time"](req, res)), responseTimeUnit: "ms", status: res.statusCode, query: req.query, params: req.params, extended: req.extendedLog, traceId, spanId, traceFlags, }; // in case of error requests if (res.statusCode >= 400) { logEntry.severity = LogLevel.ERROR; try { logEntry.responseBody = JSON.parse(res.responseBody); } catch { logEntry.responseBody = res.responseBody; } logEntry.body = sensitiveRoutes.some((route) => req.url.includes(route)) ? "*" : req.body; } return JSON.stringify(logEntry); }; } module.exports = { genLogFormatFunc };