mirror of
https://github.com/pyscript/pyscript.git
synced 2026-04-11 05:00:28 -04:00
Improve JS logging (#743)
This PR tries to improve and rationalize what we log. Key points:
- introduce `logger.ts`: each file/component is encouraged to use the logger instead of writing directly to `console.*`
* the logger automatically prepend a prefix like `[py-config]`, `[py-env]` which make it easier to understand where a certain message is printed from
* it provide a central place where to add more features in the future. E.g., I can imagine having a config setting to completely silence the logs (not implemented yet)
- use the new loggers everywhere
- write to `.info()` instead of `.log()`. The idea is to keep `console.log` free, so that for the users it's easier to tell apart their own messages and the pyscript ones
- generally improve what we log. This is an endless exercise, but I tried to print more things which are useful to understand what's going on and in which order the various things are executed, and remove prints which were clearly debugging leftovers
This commit is contained in:
@@ -2,6 +2,9 @@ import { runtimeLoaded } from '../stores';
|
||||
import { guidGenerator, addClasses, removeClasses } from '../utils';
|
||||
|
||||
import type { Runtime } from '../runtime';
|
||||
import { getLogger } from '../logger';
|
||||
|
||||
const logger = getLogger('pyscript/base');
|
||||
|
||||
// Global `Runtime` that implements the generic runtimes API
|
||||
let runtime: Runtime;
|
||||
@@ -49,7 +52,7 @@ export class BaseEvalElement extends HTMLElement {
|
||||
this.appendOutput = false;
|
||||
break;
|
||||
default:
|
||||
console.log(`${this.id}: custom output-modes are currently not implemented`);
|
||||
logger.warn(`${this.id}: custom output-modes are currently not implemented`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,7 +107,7 @@ export class BaseEvalElement extends HTMLElement {
|
||||
// "can't read 'name' of undefined" at import time
|
||||
imports[name] = { ...(await import(url)) };
|
||||
} catch {
|
||||
console.error(`failed to fetch '${url}' for '${name}'`);
|
||||
logger.error(`failed to fetch '${url}' for '${name}'`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -113,7 +116,6 @@ export class BaseEvalElement extends HTMLElement {
|
||||
}
|
||||
|
||||
async evaluate(): Promise<void> {
|
||||
console.log('evaluate');
|
||||
this.preEvaluate();
|
||||
|
||||
let source: string;
|
||||
@@ -158,7 +160,7 @@ export class BaseEvalElement extends HTMLElement {
|
||||
|
||||
this.postEvaluate();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
logger.error(err);
|
||||
try{
|
||||
if (Element === undefined) {
|
||||
Element = <Element>runtime.globals.get('Element');
|
||||
@@ -177,7 +179,7 @@ export class BaseEvalElement extends HTMLElement {
|
||||
this.errorElement.style.display = 'block';
|
||||
this.errorElement.style.visibility = 'visible';
|
||||
} catch (internalErr){
|
||||
console.error("Unnable to write error to error element in page.")
|
||||
logger.error("Unnable to write error to error element in page.")
|
||||
}
|
||||
|
||||
}
|
||||
@@ -187,10 +189,10 @@ export class BaseEvalElement extends HTMLElement {
|
||||
try {
|
||||
const output = await runtime.run(source);
|
||||
if (output !== undefined) {
|
||||
console.log(output);
|
||||
logger.info(output);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
logger.error(err);
|
||||
}
|
||||
} // end eval
|
||||
|
||||
@@ -241,14 +243,12 @@ function createWidget(name: string, code: string, klass: string) {
|
||||
// })();
|
||||
// }, 2000);
|
||||
runtimeLoaded.subscribe(value => {
|
||||
console.log('RUNTIME READY', value);
|
||||
if ('run' in value) {
|
||||
runtime = value;
|
||||
setTimeout(() => {
|
||||
void (async () => {
|
||||
await this.eval(this.code);
|
||||
this.proxy = this.proxyClass(this);
|
||||
console.log('proxy', this.proxy);
|
||||
this.proxy.connect();
|
||||
this.registerWidget();
|
||||
})();
|
||||
@@ -258,7 +258,7 @@ function createWidget(name: string, code: string, klass: string) {
|
||||
}
|
||||
|
||||
registerWidget() {
|
||||
console.log('new widget registered:', this.name);
|
||||
logger.info('new widget registered:', this.name);
|
||||
runtime.globals.set(this.id, this.proxy);
|
||||
}
|
||||
|
||||
@@ -267,10 +267,10 @@ function createWidget(name: string, code: string, klass: string) {
|
||||
const output = await runtime.run(source);
|
||||
this.proxyClass = runtime.globals.get(this.klass);
|
||||
if (output !== undefined) {
|
||||
console.log(output);
|
||||
logger.info('CustomWidget.eval: ', output);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
logger.error('CustomWidget.eval: ', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -319,7 +319,7 @@ export class PyWidget extends HTMLElement {
|
||||
const mainDiv = document.createElement('div');
|
||||
mainDiv.id = this.id + '-main';
|
||||
this.appendChild(mainDiv);
|
||||
console.log('reading source');
|
||||
logger.debug('PyWidget: reading source', this.source);
|
||||
this.code = await this.getSourceFromFile(this.source);
|
||||
createWidget(this.name, this.code, this.klass);
|
||||
}
|
||||
@@ -361,10 +361,10 @@ export class PyWidget extends HTMLElement {
|
||||
try {
|
||||
const output = await runtime.run(source);
|
||||
if (output !== undefined) {
|
||||
console.log(output);
|
||||
logger.info('PyWidget.eval: ', output);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
logger.error('PyWidget.eval: ', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { addClasses } from '../utils';
|
||||
import { getLogger } from '../logger';
|
||||
|
||||
const logger = getLogger('py-box');
|
||||
|
||||
export class PyBox extends HTMLElement {
|
||||
shadow: ShadowRoot;
|
||||
@@ -24,7 +27,6 @@ export class PyBox extends HTMLElement {
|
||||
// meaning that we end up with 2 editors, if there's a <py-repl> inside the <py-box>
|
||||
// so, if we have more than 2 children with the cm-editor class, we remove one of them
|
||||
while (this.childNodes.length > 0) {
|
||||
console.log(this.firstChild);
|
||||
if (this.firstChild.nodeName == 'PY-REPL') {
|
||||
// in this case we need to remove the child and create a new one from scratch
|
||||
const replDiv = document.createElement('div');
|
||||
@@ -61,6 +63,6 @@ export class PyBox extends HTMLElement {
|
||||
});
|
||||
|
||||
this.appendChild(mainDiv);
|
||||
console.log('py-box connected');
|
||||
logger.info('py-box connected');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { BaseEvalElement } from './base';
|
||||
import { addClasses, htmlDecode } from '../utils';
|
||||
import { getLogger } from '../logger'
|
||||
|
||||
const logger = getLogger('py-button');
|
||||
|
||||
|
||||
export class PyButton extends BaseEvalElement {
|
||||
widths: Array<string>;
|
||||
@@ -65,9 +69,9 @@ export class PyButton extends BaseEvalElement {
|
||||
this.runAfterRuntimeInitialized(async () => {
|
||||
await this.eval(this.code);
|
||||
await this.eval(registrationCode);
|
||||
console.log('registered handlers');
|
||||
logger.debug('registered handlers');
|
||||
});
|
||||
|
||||
console.log('py-button connected');
|
||||
logger.debug('py-button connected');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,9 @@ import { BaseEvalElement } from './base';
|
||||
import { appConfig } from '../stores';
|
||||
import type { AppConfig, Runtime } from '../runtime';
|
||||
import { PyodideRuntime, DEFAULT_RUNTIME_CONFIG } from '../pyodide';
|
||||
import { getLogger } from '../logger';
|
||||
|
||||
const logger = getLogger('py-config');
|
||||
|
||||
/**
|
||||
* Configures general metadata about the PyScript application such
|
||||
@@ -41,7 +44,7 @@ export class PyConfig extends BaseEvalElement {
|
||||
}
|
||||
|
||||
appConfig.set(this.values);
|
||||
console.log('config set', this.values);
|
||||
logger.info('config set:', this.values);
|
||||
|
||||
this.loadRuntimes();
|
||||
}
|
||||
@@ -57,7 +60,7 @@ export class PyConfig extends BaseEvalElement {
|
||||
}
|
||||
|
||||
loadRuntimes() {
|
||||
console.log('Initializing runtimes...');
|
||||
logger.info('Initializing runtimes');
|
||||
for (const runtime of this.values.runtimes) {
|
||||
const runtimeObj: Runtime = new PyodideRuntime(runtime.src, runtime.name, runtime.lang);
|
||||
const script = document.createElement('script'); // create a script DOM node
|
||||
|
||||
@@ -3,13 +3,15 @@ import * as jsyaml from 'js-yaml';
|
||||
import { runtimeLoaded, addInitializer } from '../stores';
|
||||
import { handleFetchError } from '../utils';
|
||||
import type { Runtime } from '../runtime';
|
||||
import { getLogger } from '../logger';
|
||||
|
||||
const logger = getLogger('py-env');
|
||||
|
||||
// Premise used to connect to the first available runtime (can be pyodide or others)
|
||||
let runtime: Runtime;
|
||||
|
||||
runtimeLoaded.subscribe(value => {
|
||||
runtime = value;
|
||||
console.log('RUNTIME READY');
|
||||
});
|
||||
|
||||
export class PyEnv extends HTMLElement {
|
||||
@@ -55,13 +57,14 @@ export class PyEnv extends HTMLElement {
|
||||
this.paths = paths;
|
||||
|
||||
async function loadEnv() {
|
||||
logger.info("Loading env: ", env);
|
||||
await runtime.installPackage(env);
|
||||
console.log('environment loaded');
|
||||
}
|
||||
|
||||
async function loadPaths() {
|
||||
logger.info("Paths to load: ", paths)
|
||||
for (const singleFile of paths) {
|
||||
console.log(`loading ${singleFile}`);
|
||||
logger.info(` loading path: ${singleFile}`);
|
||||
try {
|
||||
await runtime.loadFromFile(singleFile);
|
||||
} catch (e) {
|
||||
@@ -69,11 +72,10 @@ export class PyEnv extends HTMLElement {
|
||||
handleFetchError(<Error>e, singleFile);
|
||||
}
|
||||
}
|
||||
console.log('paths loaded');
|
||||
logger.info("All paths loaded");
|
||||
}
|
||||
|
||||
addInitializer(loadEnv);
|
||||
addInitializer(loadPaths);
|
||||
console.log('environment loading...', this.env);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { BaseEvalElement } from './base';
|
||||
import { addClasses, htmlDecode } from '../utils';
|
||||
import { getLogger } from '../logger'
|
||||
|
||||
const logger = getLogger('py-inputbox');
|
||||
|
||||
export class PyInputBox extends BaseEvalElement {
|
||||
widths: Array<string>;
|
||||
@@ -43,7 +46,7 @@ export class PyInputBox extends BaseEvalElement {
|
||||
this.runAfterRuntimeInitialized(async () => {
|
||||
await this.eval(this.code);
|
||||
await this.eval(registrationCode);
|
||||
console.log('registered handlers');
|
||||
logger.debug('registered handlers');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { BaseEvalElement } from './base';
|
||||
import { getLogger } from '../logger';
|
||||
|
||||
const logger = getLogger('py-loader');
|
||||
|
||||
export class PyLoader extends BaseEvalElement {
|
||||
widths: Array<string>;
|
||||
@@ -26,12 +29,15 @@ export class PyLoader extends BaseEvalElement {
|
||||
}
|
||||
|
||||
log(msg: string) {
|
||||
// loader messages are showed both in the HTML and in the console
|
||||
logger.info(msg);
|
||||
const newLog = document.createElement('p');
|
||||
newLog.innerText = msg;
|
||||
this.details.appendChild(newLog);
|
||||
}
|
||||
|
||||
close() {
|
||||
logger.info('Closing');
|
||||
this.remove();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,9 @@ import { defaultKeymap } from '@codemirror/commands';
|
||||
import { oneDarkTheme } from '@codemirror/theme-one-dark';
|
||||
import { addClasses, htmlDecode } from '../utils';
|
||||
import { BaseEvalElement } from './base';
|
||||
import { getLogger } from '../logger';
|
||||
|
||||
const logger = getLogger('py-repl');
|
||||
|
||||
|
||||
function createCmdHandler(el: PyRepl): StateCommand {
|
||||
@@ -102,8 +105,8 @@ export class PyRepl extends BaseEvalElement {
|
||||
});
|
||||
|
||||
if (!this.id) {
|
||||
console.log(
|
||||
"WARNING: <pyrepl> define with an id. <pyrepl> should always have an id. More than one <pyrepl> on a page won't work otherwise!",
|
||||
logger.warn(
|
||||
"WARNING: <py-repl> defined without an id. <py-repl> should always have an id, otherwise multiple <py-repl> in the same page will not work!"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -139,7 +142,7 @@ export class PyRepl extends BaseEvalElement {
|
||||
|
||||
this.appendChild(mainDiv);
|
||||
this.editor.focus();
|
||||
console.log('connected');
|
||||
logger.debug(`element ${this.id} successfully connected`);
|
||||
}
|
||||
|
||||
addToOutput(s: string): void {
|
||||
@@ -195,8 +198,4 @@ export class PyRepl extends BaseEvalElement {
|
||||
getSourceFromElement(): string {
|
||||
return this.editor.state.doc.toString();
|
||||
}
|
||||
|
||||
render() {
|
||||
console.log('rendered');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,9 @@ import {
|
||||
import { addClasses, htmlDecode } from '../utils';
|
||||
import { BaseEvalElement } from './base';
|
||||
import type { Runtime } from '../runtime';
|
||||
import { getLogger } from '../logger';
|
||||
|
||||
const logger = getLogger('py-script');
|
||||
|
||||
// Premise used to connect to the first available runtime (can be pyodide or others)
|
||||
let runtime: Runtime;
|
||||
@@ -72,8 +75,6 @@ export class PyScript extends BaseEvalElement {
|
||||
this.appendChild(mainDiv);
|
||||
addToScriptsQueue(this);
|
||||
|
||||
console.log('connected');
|
||||
|
||||
if (this.hasAttribute('src')) {
|
||||
this.source = this.getAttribute('src');
|
||||
}
|
||||
@@ -100,7 +101,7 @@ export class PyScript extends BaseEvalElement {
|
||||
// "can't read 'name' of undefined" at import time
|
||||
exports = { ...(await import(url)) };
|
||||
} catch {
|
||||
console.warn(`failed to fetch '${url}' for '${name}'`);
|
||||
logger.warn(`failed to fetch '${url}' for '${name}'`);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -209,9 +210,9 @@ const pyAttributeToEvent: Map<string, string> = new Map<string, string>([
|
||||
["py-toggle", "toggle"],
|
||||
]);
|
||||
|
||||
/** Initialize all elements with py-on* handlers attributes */
|
||||
/** Initialize all elements with py-* handlers attributes */
|
||||
async function initHandlers() {
|
||||
console.log('Collecting nodes...');
|
||||
logger.debug('Initializing py-* event handlers...');
|
||||
for (const pyAttribute of pyAttributeToEvent.keys()) {
|
||||
await createElementsWithEventListeners(runtime, pyAttribute);
|
||||
}
|
||||
@@ -251,8 +252,8 @@ async function createElementsWithEventListeners(runtime: Runtime, pyAttribute: s
|
||||
|
||||
/** Mount all elements with attribute py-mount into the Python namespace */
|
||||
async function mountElements() {
|
||||
console.log('Collecting nodes to be mounted into python namespace...');
|
||||
const matches: NodeListOf<HTMLElement> = document.querySelectorAll('[py-mount]');
|
||||
logger.info(`py-mount: found ${matches.length} elements`);
|
||||
|
||||
let source = '';
|
||||
for (const el of matches) {
|
||||
|
||||
Reference in New Issue
Block a user