gle
Version:
Global Log Engine: Environment-agnostic debugging & logging utility
52 lines (51 loc) • 1.95 kB
JavaScript
import wildcard from "wildcard";
import prettyMS from "pretty-ms";
import { getNextColour } from "./colour.js";
import { getDebugContextPatterns } from "./env.js";
import { convertArguments } from "./conversion.js";
import { styleLogLine } from "./compat.js";
import { getLogRenderer } from "./render.js";
let __contextPatterns = null, __contexts = {};
const __logColours = {};
const __logTimes = {};
export function createLog(context) {
if (!resolveContext(context))
return (...logArgs) => { };
const colour = __logColours[context] = (__logColours[context] || getNextColour());
return function __log(...logArgs) {
renderLog(context, logArgs, colour);
};
}
export function log(context, ...logArgs) {
if (!resolveContext(context))
return;
const colour = __logColours[context] = (__logColours[context] || getNextColour());
renderLog(context, logArgs, colour);
}
function renderLog(context, logArgs, colour) {
const lastContextTime = __logTimes[context] ? __logTimes[context] : Date.now();
const now = __logTimes[context] = Date.now();
const timeSinceLast = Math.max(0, now - lastContextTime);
const text = convertArguments(logArgs, " ");
const callArgs = styleLogLine(context, text, `+${prettyMS(timeSinceLast, { compact: true })}`, colour);
const renderLog = getLogRenderer();
renderLog(...callArgs);
}
function resolveContext(context) {
if (!__contextPatterns) {
__contextPatterns = getDebugContextPatterns();
}
if (typeof __contexts[context] === "undefined") {
for (const pattern in __contextPatterns) {
if (!wildcard(pattern, context))
continue;
__contexts[context] = !!__contextPatterns[pattern];
if (!__contexts[context])
break;
}
}
return __contexts[context];
}
export function toggleContext(context, enabled) {
__contexts[context] = enabled;
}