kaiwyvern.notes
← Notes

logger

plugins/sys/logger/main.js

A plugin loader ends up with a hundred modules writing to the same console. The logger exists to answer one question fast: which module printed this line.

One call, no arguments in the way

Every module creates its own logger at import time and passes import.meta.url. The path is trimmed and turned into the prefix, so call sites stay clean: log.info('...') without repeating the module name.

export function createLogger(moduleUrl) {
    const path = moduleUrl.replace('https://plugins/', '');
    const prefix = `[${path}]`;
    const colorName = MODULE_COLORS[path];
    const color = colorName && COLORS[colorName] ? COLORS[colorName] : '';

    return {
        debug: (msg, ...args) => console.debug(`${COLORS.gray}${prefix}${COLORS.reset} ${msg}`, ...args),
        info:  (msg, ...args) => console.log(`${color}${prefix}${COLORS.reset} ${msg}`, ...args),
        warn:  (msg, ...args) => console.warn(`${COLORS.yellow}${prefix}${COLORS.reset} ${msg}`, ...args),
        error: (msg, ...args) => console.error(`${COLORS.red}${prefix}${COLORS.reset} ${msg}`, ...args)
    };
}

Why the level has a fixed colour

The level is encoded twice: by the console method (so the DevTools filter works) and by the colour (so the eye catches it while scrolling). Grey is reserved for debug — it stays readable but never competes with warnings.

const COLORS = {
    reset: '\x1b[0m',  red: '\x1b[31m',  green: '\x1b[32m',
    yellow: '\x1b[33m', blue: '\x1b[34m', magenta: '\x1b[35m',
    cyan: '\x1b[36m',  white: '\x1b[37m', gray: '\x1b[90m'
};

The module table

Colours are not random: they follow the folder. Entry points (index.js) are yellow, service modules are blue, small helpers are cyan, and low-level libraries are magenta or grey. Same folder — same colour, so a burst of lines can be attributed to an area without reading the paths.

const MODULE_COLORS = {
    'module/index.js': 'yellow',
    'module/push/main.js': 'blue',

    'sys/logger/main.js': 'gray',
    'sys/gamestate/main.js': 'blue',
    'sys/gamestate/LCUX/mode.js': 'cyan',

    'ui-shared/main.js': 'gray'
};

Unknown module

If a path is missing from the table, the logger still works: color becomes an empty string and the prefix is printed unstyled. A new module therefore never breaks logging, it only looks plain until someone adds a colour.

Usage

import { createLogger } from 'https://plugins/sys/logger/main.js';

const log = createLogger(import.meta.url);

log.info('shim started');        // [sys/gamestate/LCUX/mode.js] shim started
log.warn('socket is missing');   // yellow
log.error('failed to parse', e); // red + the error object