44 lines
1.6 KiB
JavaScript
44 lines
1.6 KiB
JavaScript
// src/middleware/logger/index.ts
|
|
import { getColorEnabled } from "../../utils/color.js";
|
|
import { getPath } from "../../utils/url.js";
|
|
var humanize = (times) => {
|
|
const [delimiter, separator] = [",", "."];
|
|
const orderTimes = times.map((v) => v.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + delimiter));
|
|
return orderTimes.join(separator);
|
|
};
|
|
var time = (start) => {
|
|
const delta = Date.now() - start;
|
|
return humanize([delta < 1e3 ? delta + "ms" : Math.round(delta / 1e3) + "s"]);
|
|
};
|
|
var colorStatus = (status) => {
|
|
const colorEnabled = getColorEnabled();
|
|
const out = {
|
|
7: colorEnabled ? `\x1B[35m${status}\x1B[0m` : `${status}`,
|
|
5: colorEnabled ? `\x1B[31m${status}\x1B[0m` : `${status}`,
|
|
4: colorEnabled ? `\x1B[33m${status}\x1B[0m` : `${status}`,
|
|
3: colorEnabled ? `\x1B[36m${status}\x1B[0m` : `${status}`,
|
|
2: colorEnabled ? `\x1B[32m${status}\x1B[0m` : `${status}`,
|
|
1: colorEnabled ? `\x1B[32m${status}\x1B[0m` : `${status}`,
|
|
0: colorEnabled ? `\x1B[33m${status}\x1B[0m` : `${status}`
|
|
};
|
|
const calculateStatus = status / 100 | 0;
|
|
return out[calculateStatus];
|
|
};
|
|
function log(fn, prefix, method, path, status = 0, elapsed) {
|
|
const out = prefix === "<--" /* Incoming */ ? ` ${prefix} ${method} ${path}` : ` ${prefix} ${method} ${path} ${colorStatus(status)} ${elapsed}`;
|
|
fn(out);
|
|
}
|
|
var logger = (fn = console.log) => {
|
|
return async function logger2(c, next) {
|
|
const { method } = c.req;
|
|
const path = getPath(c.req.raw);
|
|
log(fn, "<--" /* Incoming */, method, path);
|
|
const start = Date.now();
|
|
await next();
|
|
log(fn, "-->" /* Outgoing */, method, path, c.res.status, time(start));
|
|
};
|
|
};
|
|
export {
|
|
logger
|
|
};
|