Wifiv2 / src /utils /logger.js
Mbonea's picture
Add runtime log filters for startup and migrations
2324ed0
Raw
History Blame Contribute Delete
1.64 kB
const DEFAULT_DISABLED_TYPES = ['env', 'migrate', 'migration'];
function normalizeType(value) {
return String(value || '')
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}
function parseTypeList(value) {
return new Set(
String(value || '')
.split(',')
.map(normalizeType)
.filter(Boolean)
);
}
function configuredSets() {
const enabled = parseTypeList(process.env.LOG_ENABLED_TYPES);
const disabled = parseTypeList(process.env.LOG_DISABLED_TYPES || DEFAULT_DISABLED_TYPES.join(','));
return { enabled, disabled };
}
function typeFromMessage(args) {
const first = args[0];
if (typeof first !== 'string') return null;
const match = first.match(/^\[([^\]]+)\]/);
return match ? normalizeType(match[1]) : null;
}
function isTypeEnabled(type) {
if (!type) return true;
const { enabled, disabled } = configuredSets();
if (enabled.has('all') || enabled.has(type)) return true;
if (disabled.has('all') || disabled.has(type)) return false;
return true;
}
function shouldLog(args) {
return isTypeEnabled(typeFromMessage(args));
}
function install() {
if (console.__wifiBizLoggerInstalled) return;
for (const method of ['log', 'warn', 'error', 'info', 'debug']) {
const original = console[method]?.bind(console);
if (!original) continue;
console[method] = (...args) => {
if (shouldLog(args)) {
original(...args);
}
};
}
Object.defineProperty(console, '__wifiBizLoggerInstalled', {
value: true,
enumerable: false,
});
}
module.exports = {
install,
isTypeEnabled,
normalizeType,
};