Files
pyscript/pyscriptjs/src/logger.ts
Hood Chatham 37c9db09c6 Fix many ESlint errors (#1265)
* Unvendor toml package

* Fix many ESlint errors

For mysterious reasons, these errors appear on my branch #1262 even
though they are not related to changes there. The eslint config seems
a bit unstable.

Anyways this fixes them.

* Put back Record

* Fix typescript compilation

* Fix lints

* Try @iarna/toml instead

* Fix import

* Use @ltd/j-toml

* Update test

* Use toml-j0.4

* Some changes

* Fix toml import

* Try adding eslint gha job

* Add forgotten checkout action

* Force CI to run

* Blah

* Fix

* Revert changes to github workflow

* Fix lints

* wget toml-j0.4 type definitions

* Add toml-j types workaround to eslint workflow

* Apply formatter

* Use @hoodmane/toml-j0.4

* Import from @hoodmane/toml-j0.4
2023-03-13 15:51:28 +01:00

65 lines
1.8 KiB
TypeScript

/* Very simple logger interface.
Each module is expected to create its own logger by doing e.g.:
const logger = getLogger('my-prefix');
and then use it instead of console:
logger.info('hello', 'world');
logger.warn('...');
logger.error('...');
The logger automatically adds the prefix "[my-prefix]" to all logs.
E.g., the above call would print:
[my-prefix] hello world
logger.log is intentionally omitted. The idea is that PyScript should not
write anything to console.log, to leave it free for the user.
Currently, the logger does not to anything more than that. In the future,
we might want to add additional features such as the ability to
enable/disable logs on a global or per-module basis.
*/
interface Logger {
debug(message: string, ...args: unknown[]): void;
info(message: string, ...args: unknown[]): void;
warn(message: string, ...args: unknown[]): void;
error(message: string | Error, ...args: unknown[]): void;
}
const _cache = new Map<string, Logger>();
function getLogger(prefix: string): Logger {
let logger = _cache.get(prefix);
if (logger === undefined) {
logger = _makeLogger(prefix);
_cache.set(prefix, logger);
}
return logger;
}
function _makeLogger(prefix: string): Logger {
prefix = `[${prefix}] `;
function make(level: 'info' | 'debug' | 'warn' | 'error') {
const out_fn = console[level].bind(console) as typeof console.log;
function fn(fmt: string, ...args: unknown[]) {
out_fn(prefix + fmt, ...args);
}
return fn;
}
// 'log' is intentionally omitted
const debug = make('debug');
const info = make('info');
const warn = make('warn');
const error = make('error');
return { debug, info, warn, error };
}
export { getLogger };