koa-mongo-router
Version:
KOA REST API Router for MongoDB
53 lines (52 loc) • 1.86 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.koaLogger = void 0;
const http_1 = require("http");
const node_server_utils_1 = require("node-server-utils");
async function koaLogger(ctx, next) {
const start = process.hrtime();
await next();
ctx.response.res.on('finish', () => {
const diff = process.hrtime(start);
const time = Math.round((diff[0] * 1e9 + diff[1]) / 1000000);
let url = ctx.url;
const queryIndex = url.indexOf('?');
if (queryIndex !== -1) {
url = url.substr(0, queryIndex);
}
const logObject = {
message: http_1.STATUS_CODES[ctx.response.status],
status: ctx.response.status,
method: ctx.method,
url,
};
if (ctx.request.querystring != undefined && ctx.request.querystring !== '') {
try {
logObject.query = decodeURIComponent(ctx.request.querystring);
} /* istanbul ignore next */
catch (_a) {
/**/
}
}
/* istanbul ignore else */
if (time != undefined) {
logObject.time = time;
}
/* istanbul ignore if */
if (ctx.state != undefined && ctx.state.error instanceof Error) {
logObject.error = ctx.state.error.message;
logObject.errorName = ctx.state.error.name;
logObject.stack = ctx.state.error.stack.split('\n');
}
/* istanbul ignore else */
if (ctx.response.status < 400) {
node_server_utils_1.logger.info(logObject);
}
else if (ctx.response.status < 500) {
node_server_utils_1.logger.warn(logObject);
}
else {
node_server_utils_1.logger.error(logObject);
}
});
}
exports.koaLogger = koaLogger;