From 995ee2c411e942ce358c91e724fa58d2890e858d Mon Sep 17 00:00:00 2001 From: Richard Knoll Date: Wed, 30 Oct 2024 10:46:10 -0700 Subject: [PATCH] Refactor all logging to go through a logger object (#10249) * refactor all logging to go through a logger object * revert accidental replaces * pr feedback --- pxtblocks/codecardRenderer.ts | 2 +- pxtblocks/compiler/util.ts | 6 +- pxtblocks/diff.ts | 2 +- pxtblocks/fields/fieldEditorRegistry.ts | 2 +- pxtblocks/fields/field_numberdropdown.ts | 2 +- pxtblocks/fields/field_textdropdown.ts | 8 +-- pxtblocks/fields/field_tileset.ts | 2 +- pxtblocks/importer.ts | 2 +- pxtblocks/layout.ts | 2 +- pxtblocks/legacyMutations.ts | 12 ++-- pxtblocks/loader.ts | 8 +-- .../blocks/functionDeclarationBlock.ts | 2 +- pxtblocks/plugins/functions/extensions.ts | 2 +- .../plugins/functions/functionManager.ts | 2 +- pxtblocks/plugins/functions/utils.ts | 2 +- pxtcompiler/emitter/backbase.ts | 24 +++---- pxtcompiler/emitter/backjs.ts | 4 +- pxtcompiler/emitter/backvm.ts | 16 ++--- pxtcompiler/emitter/emitter.ts | 14 ++-- pxtcompiler/emitter/esp.ts | 2 +- pxtcompiler/emitter/formatter.ts | 4 +- pxtcompiler/emitter/hexfile.ts | 4 +- pxtcompiler/emitter/ir.ts | 12 ++-- pxtcompiler/emitter/service.ts | 10 +-- pxtcompiler/simpledriver.ts | 10 +-- pxtcompiler/simshim.ts | 4 +- pxteditor/editorcontroller.ts | 2 +- pxtlib/analytics.ts | 2 +- pxtlib/browserutils.ts | 18 ++--- pxtlib/color.ts | 2 +- pxtlib/commonutil.ts | 9 +-- pxtlib/cpp.ts | 8 +-- pxtlib/diff.ts | 2 +- pxtlib/docsrender.ts | 3 +- pxtlib/emitter/assembler.ts | 12 ++-- pxtlib/gdbserver.ts | 2 +- pxtlib/hf2.ts | 2 +- pxtlib/hwdbg.ts | 12 ++-- pxtlib/logger.ts | 67 +++++++++++++++++++ pxtlib/main.ts | 39 ++++------- pxtlib/semver.ts | 8 +-- pxtlib/service.ts | 14 ++-- pxtlib/tilemap.ts | 2 +- pxtlib/util.ts | 26 +++---- pxtlib/webusb.ts | 2 +- pxtpy/converter.ts | 14 ++-- pxtpy/parser.ts | 2 +- pxtrunner/debugRunner.ts | 2 +- pxtrunner/runner.ts | 22 +++--- pxtservices/editorDriver.ts | 2 +- pxtservices/iframeDriver.ts | 2 +- pxtservices/loggingService.ts | 6 +- pxtsim/allocator.ts | 22 +++--- pxtsim/debugProtocol.ts | 2 +- pxtsim/embed.ts | 4 +- pxtsim/langsupport.ts | 16 ++--- pxtsim/libgeneric.ts | 4 +- pxtsim/logger.ts | 67 +++++++++++++++++++ pxtsim/runtime.ts | 10 +-- pxtsim/simdriver.ts | 8 +-- pxtsim/simlib.ts | 2 +- pxtsim/visuals/boardhost.ts | 6 +- pxtsim/visuals/wiring.ts | 2 +- webapp/src/app.tsx | 18 ++--- webapp/src/compiler.ts | 12 ++-- webapp/src/components/tutorialValidators.tsx | 2 +- webapp/src/core.ts | 12 ++-- webapp/src/extensions.tsx | 2 +- webapp/src/gitjson.tsx | 2 +- webapp/src/greenscreen.tsx | 6 +- webapp/src/hidbridge.ts | 2 +- webapp/src/idbworkspace.ts | 2 +- webapp/src/monacoEditAmendments.ts | 8 +-- webapp/src/onboarding.ts | 2 +- webapp/src/projects.tsx | 2 +- webapp/src/simulator.ts | 2 +- webapp/src/socketbridge.ts | 2 +- webapp/src/workspace.ts | 2 +- 78 files changed, 391 insertions(+), 270 deletions(-) create mode 100644 pxtlib/logger.ts create mode 100644 pxtsim/logger.ts diff --git a/pxtblocks/codecardRenderer.ts b/pxtblocks/codecardRenderer.ts index b5e5c0db4244..d0d01383cb2d 100644 --- a/pxtblocks/codecardRenderer.ts +++ b/pxtblocks/codecardRenderer.ts @@ -59,7 +59,7 @@ export function renderCodeCard(card: pxt.CodeCard, options: CodeCardRenderOption if (card.blocksXml) { const svg = render(card.blocksXml); if (!svg) { - console.error("failed to render blocks"); + pxt.error("failed to render blocks"); pxt.debug(card.blocksXml); } else { let holder = div(img, ''); holder.setAttribute('style', 'width:100%; min-height:10em'); diff --git a/pxtblocks/compiler/util.ts b/pxtblocks/compiler/util.ts index 38ed13ebf60f..b262d4e518cf 100644 --- a/pxtblocks/compiler/util.ts +++ b/pxtblocks/compiler/util.ts @@ -25,11 +25,11 @@ export function forEachStatementInput(block: Blockly.Block, cb: (block: Blockly. export function printScope(scope: Scope, depth = 0) { const declared = Object.keys(scope.declaredVars).map(k => `${k}(${scope.declaredVars[k].id})`).join(","); const referenced = scope.referencedVars.join(", "); - console.log(`${mkIndent(depth)}SCOPE: ${scope.firstStatement ? scope.firstStatement.type : "TOP-LEVEL"}`) + pxt.log(`${mkIndent(depth)}SCOPE: ${scope.firstStatement ? scope.firstStatement.type : "TOP-LEVEL"}`) if (declared.length) { - console.log(`${mkIndent(depth)}DECS: ${declared}`) + pxt.log(`${mkIndent(depth)}DECS: ${declared}`) } - // console.log(`${mkIndent(depth)}REFS: ${referenced}`) + // pxt.log(`${mkIndent(depth)}REFS: ${referenced}`) scope.children.forEach(s => printScope(s, depth + 1)); } diff --git a/pxtblocks/diff.ts b/pxtblocks/diff.ts index c438e0ac5d18..bc2ce7aeedc2 100644 --- a/pxtblocks/diff.ts +++ b/pxtblocks/diff.ts @@ -72,7 +72,7 @@ function diffWorkspace(oldWs: Blockly.Workspace, newWs: Blockly.Workspace, optio function logger() { const log = pxt.options.debug || (window && /diffdbg=1/.test(window.location.href)) - ? console.log : (message?: any, ...args: any[]) => { }; + ? pxt.log : (message?: any, ...args: any[]) => { }; return log; } diff --git a/pxtblocks/fields/fieldEditorRegistry.ts b/pxtblocks/fields/fieldEditorRegistry.ts index 4dda51273921..1ab7d9f91146 100644 --- a/pxtblocks/fields/fieldEditorRegistry.ts +++ b/pxtblocks/fields/fieldEditorRegistry.ts @@ -82,7 +82,7 @@ export function registerFieldEditor(selector: string, field: FieldCustomConstruc export function createFieldEditor(selector: string, text: string, params: any): FieldCustom { if (registeredFieldEditors[selector] == undefined) { - console.error(`Field editor ${selector} not registered`); + pxt.error(`Field editor ${selector} not registered`); return null; } diff --git a/pxtblocks/fields/field_numberdropdown.ts b/pxtblocks/fields/field_numberdropdown.ts index c4b708e8835c..6b25f32887c4 100644 --- a/pxtblocks/fields/field_numberdropdown.ts +++ b/pxtblocks/fields/field_numberdropdown.ts @@ -208,7 +208,7 @@ function parseDropdownOptions(options: FieldTextDropdownOptions): [string, any][ return result; } else { - console.warn("Could not parse numberdropdown data field"); + pxt.warn("Could not parse numberdropdown data field"); } return []; diff --git a/pxtblocks/fields/field_textdropdown.ts b/pxtblocks/fields/field_textdropdown.ts index e2f68538d598..f69c78acf8a8 100644 --- a/pxtblocks/fields/field_textdropdown.ts +++ b/pxtblocks/fields/field_textdropdown.ts @@ -240,7 +240,7 @@ function validateOptions(options: Blockly.MenuOption[]) { const tuple = options[i]; if (!Array.isArray(tuple)) { foundError = true; - console.error( + pxt.error( 'Invalid option[' + i + ']: Each FieldDropdown option must be an ' + @@ -249,7 +249,7 @@ function validateOptions(options: Blockly.MenuOption[]) { ); } else if (typeof tuple[1] !== 'string') { foundError = true; - console.error( + pxt.error( 'Invalid option[' + i + ']: Each FieldDropdown option id must be ' + @@ -264,7 +264,7 @@ function validateOptions(options: Blockly.MenuOption[]) { typeof tuple[0].src !== 'string' ) { foundError = true; - console.error( + pxt.error( 'Invalid option[' + i + ']: Each FieldDropdown option must have a ' + @@ -323,7 +323,7 @@ function parseDropdownOptions(options: FieldTextDropdownOptions): [string, strin return result; } else { - console.warn("Could not parse textdropdown data field"); + pxt.warn("Could not parse textdropdown data field"); } } diff --git a/pxtblocks/fields/field_tileset.ts b/pxtblocks/fields/field_tileset.ts index 78b710b733b0..b68afbdad267 100644 --- a/pxtblocks/fields/field_tileset.ts +++ b/pxtblocks/fields/field_tileset.ts @@ -205,7 +205,7 @@ export class FieldTileset extends FieldImages implements FieldCustom { } if (this.sourceBlock_) { - console.warn(`Trying to set tile reference to nonexistent tile. Block type: ${this.sourceBlock_.type}, Field name: ${this.name}, Value: ${newValue}`) + pxt.warn(`Trying to set tile reference to nonexistent tile. Block type: ${this.sourceBlock_.type}, Field name: ${this.name}, Value: ${newValue}`) } return null; diff --git a/pxtblocks/importer.ts b/pxtblocks/importer.ts index d7db241d2e4e..ed0b784126df 100644 --- a/pxtblocks/importer.ts +++ b/pxtblocks/importer.ts @@ -406,7 +406,7 @@ function createBlockFromShadow(shadow: Element) { export function patchShadows(root: Element, inShadow: boolean) { if (root.tagName === "shadow") { if (root.parentElement?.tagName === "xml") { - console.warn(`Shadow block of type '${root.getAttribute("type")}' found at top level. Converting to non-shadow block`); + pxt.warn(`Shadow block of type '${root.getAttribute("type")}' found at top level. Converting to non-shadow block`); pxt.tickEvent(`blocks.import.topLevelShadow`, { blockId: root.getAttribute("type") }); const newBlock = createBlockFromShadow(root); diff --git a/pxtblocks/layout.ts b/pxtblocks/layout.ts index e374989b5c6f..4c6a4d36414e 100644 --- a/pxtblocks/layout.ts +++ b/pxtblocks/layout.ts @@ -469,7 +469,7 @@ async function convertIconsToPngAsync(xsg: Document): Promise { let href = imageIconCache[svgUri]; if (!href) { href = await pxt.BrowserUtils.encodeToPngAsync(svgUri, { width, height, pixelDensity: 2 }); - console.log(`HREF: ${href}`); + pxt.log(`HREF: ${href}`); } imageIconCache[svgUri] = href; diff --git a/pxtblocks/legacyMutations.ts b/pxtblocks/legacyMutations.ts index a63e491721af..d29cfd840b96 100644 --- a/pxtblocks/legacyMutations.ts +++ b/pxtblocks/legacyMutations.ts @@ -74,14 +74,14 @@ export function addMutation(b: MutatingBlock, info: pxtc.SymbolInfo, mutationTyp switch (mutationType) { case MutatorTypes.ObjectDestructuringMutator: if (!info.parameters || info.parameters.length < 1) { - console.error("Destructuring mutations require at least one parameter") + pxt.error("Destructuring mutations require at least one parameter") } else { let found = false; for (const param of info.parameters) { if (param.type.indexOf("=>") !== -1) { if (!param.properties || param.properties.length === 0) { - console.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties"); + pxt.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties"); return; } found = true; @@ -89,7 +89,7 @@ export function addMutation(b: MutatingBlock, info: pxtc.SymbolInfo, mutationTyp } if (!found) { - console.error("Destructuring mutations must have an event parameter"); + pxt.error("Destructuring mutations must have an event parameter"); return; } } @@ -102,7 +102,7 @@ export function addMutation(b: MutatingBlock, info: pxtc.SymbolInfo, mutationTyp m = new DefaultInstanceMutator(b, info); break; default: - console.warn("Ignoring unknown mutation type: " + mutationType); + pxt.warn("Ignoring unknown mutation type: " + mutationType); return; } @@ -126,7 +126,7 @@ export function mutateToolboxBlock(block: Node, mutationType: string, mutation: case MutatorTypes.DefaultInstanceMutator: mutationElement.setAttribute(DefaultInstanceMutator.attributeName, mutation); default: - console.warn("Ignoring unknown mutation type: " + mutationType); + pxt.warn("Ignoring unknown mutation type: " + mutationType); return; } @@ -366,7 +366,7 @@ class DestructuringMutator extends MutatorHelper { this.parameterRenames = JSON.parse(xmlElement.getAttribute(DestructuringMutator.renameAttributeName)); } catch (e) { - console.warn("Ignoring invalid rename map in saved block mutation"); + pxt.warn("Ignoring invalid rename map in saved block mutation"); } } diff --git a/pxtblocks/loader.ts b/pxtblocks/loader.ts index 495abc70d1b7..4dd518c00d80 100644 --- a/pxtblocks/loader.ts +++ b/pxtblocks/loader.ts @@ -135,7 +135,7 @@ function injectBlockDefinition(info: pxtc.BlocksInfo, fn: pxtc.SymbolInfo, comp: } if (Blockly.Blocks[fn.attributes.blockId]) { - console.error("duplicate block definition: " + id); + pxt.error("duplicate block definition: " + id); return false; } @@ -342,7 +342,7 @@ function initBlock(block: Blockly.Block, info: pxtc.BlocksInfo, fn: pxtc.SymbolI if (fn.attributes.shim === "ENUM_GET" || fn.attributes.shim === "KIND_GET") { if (comp.parameters.length > 1 || comp.thisParameter) { - console.warn(`Enum blocks may only have 1 parameter but ${fn.attributes.blockId} has ${comp.parameters.length}`); + pxt.warn(`Enum blocks may only have 1 parameter but ${fn.attributes.blockId} has ${comp.parameters.length}`); return; } } @@ -383,7 +383,7 @@ function initBlock(block: Blockly.Block, info: pxtc.BlocksInfo, fn: pxtc.SymbolI firstParam = false; if (!pr) { - console.error("block " + fn.attributes.blockId + ": unknown parameter " + part.name + (part.ref ? ` (${part.ref})` : "")); + pxt.error("block " + fn.attributes.blockId + ": unknown parameter " + part.name + (part.ref ? ` (${part.ref})` : "")); return; } @@ -424,7 +424,7 @@ function initBlock(block: Blockly.Block, info: pxtc.BlocksInfo, fn: pxtc.SymbolI } if (syms.length == 0) { - console.error(`no instances of ${typeInfo.qName} found`) + pxt.error(`no instances of ${typeInfo.qName} found`) } const dd: Blockly.MenuOption[] = syms.map(v => { let k = v.attributes.block || v.attributes.blockId || v.name; diff --git a/pxtblocks/plugins/functions/blocks/functionDeclarationBlock.ts b/pxtblocks/plugins/functions/blocks/functionDeclarationBlock.ts index 0ad252c37986..5046113f7690 100644 --- a/pxtblocks/plugins/functions/blocks/functionDeclarationBlock.ts +++ b/pxtblocks/plugins/functions/blocks/functionDeclarationBlock.ts @@ -211,7 +211,7 @@ const FUNCTION_DECLARATION_MIXIN: FunctionDeclarationMixin = { }); break; default: - console.warn("Unexpected input type on a function mutator root: " + input.type); + pxt.warn("Unexpected input type on a function mutator root: " + input.type); } } }, diff --git a/pxtblocks/plugins/functions/extensions.ts b/pxtblocks/plugins/functions/extensions.ts index a667125a3f60..fad8e76956f1 100644 --- a/pxtblocks/plugins/functions/extensions.ts +++ b/pxtblocks/plugins/functions/extensions.ts @@ -99,7 +99,7 @@ const variableReporterMixin = { callback: () => { let variableField = this.getField('VAR') as Blockly.FieldVariable; if (!variableField) { - console.log("Tried to get a variable field on the wrong type of block."); + pxt.log("Tried to get a variable field on the wrong type of block."); } variableField.setValue(variable.getId()); } diff --git a/pxtblocks/plugins/functions/functionManager.ts b/pxtblocks/plugins/functions/functionManager.ts index c35ef8386ce1..4e86499692ce 100644 --- a/pxtblocks/plugins/functions/functionManager.ts +++ b/pxtblocks/plugins/functions/functionManager.ts @@ -46,7 +46,7 @@ export class FunctionManager { this._editFunctionExternal(mutation, cb); } else { - console.warn('External function editor must be overriden: Blockly.Functions.editFunctionExternalHandler', mutation, cb); + pxt.warn('External function editor must be overriden: Blockly.Functions.editFunctionExternalHandler', mutation, cb); } } } diff --git a/pxtblocks/plugins/functions/utils.ts b/pxtblocks/plugins/functions/utils.ts index 3e9272b45dd2..45e8aefec6cc 100644 --- a/pxtblocks/plugins/functions/utils.ts +++ b/pxtblocks/plugins/functions/utils.ts @@ -241,7 +241,7 @@ export function mutateCallersAndDefinition(name: string, ws: Blockly.Workspace, }); Blockly.Events.setGroup(false); } else { - console.warn("Attempted to change function " + name + ", but no definition block was found on the workspace"); + pxt.warn("Attempted to change function " + name + ", but no definition block was found on the workspace"); } } diff --git a/pxtcompiler/emitter/backbase.ts b/pxtcompiler/emitter/backbase.ts index e24ea16ca203..a4bba8fb7bbd 100644 --- a/pxtcompiler/emitter/backbase.ts +++ b/pxtcompiler/emitter/backbase.ts @@ -283,8 +283,8 @@ ${baseLabel}_nochk: if (bi) { let off = U.lookup(th.stackAtLabel, `__brkp_${bi.id}`) if (off !== this.proc.debugInfo.localsMark) { - console.log(bi) - console.log(th.stackAtLabel) + pxt.log(bi) + pxt.log(th.stackAtLabel) U.oops(`offset doesn't match: ${off} != ${this.proc.debugInfo.localsMark}`) } } @@ -312,7 +312,7 @@ ${baseLabel}_nochk: for (let i = 0; i < this.proc.body.length; ++i) { let s = this.proc.body[i] - // console.log("STMT", s.toString()) + // pxt.log("STMT", s.toString()) switch (s.stmtKind) { case ir.SK.Expr: this.emitExpr(s.expr) @@ -320,9 +320,9 @@ ${baseLabel}_nochk: case ir.SK.StackEmpty: if (this.exprStack.length > 0) { for (let stmt of this.proc.body.slice(i - 4, i + 1)) - console.log(`PREVSTMT ${stmt.toString().trim()}`) + pxt.log(`PREVSTMT ${stmt.toString().trim()}`) for (let e of this.exprStack) - console.log(`EXPRSTACK ${e.currUses}/${e.totalUses} E: ${e.toString()}`) + pxt.log(`EXPRSTACK ${e.currUses}/${e.totalUses} E: ${e.toString()}`) oops("stack should be empty") } this.write("@stackempty locals") @@ -387,7 +387,7 @@ ${baseLabel}_nochk: private terminate(expr: ir.Expr) { assert(expr.exprKind == ir.EK.SharedRef) let arg = expr.args[0] - // console.log("TERM", arg.sharingInfo(), arg.toString(), this.dumpStack()) + // pxt.log("TERM", arg.sharingInfo(), arg.toString(), this.dumpStack()) U.assert(arg.currUses != arg.totalUses) // we should have the terminated expression on top U.assert(this.exprStack[0] === arg, "term at top") @@ -407,14 +407,14 @@ ${baseLabel}_nochk: } private validateJmpStack(lbl: ir.Stmt, off = 0) { - // console.log("Validate:", off, lbl.lblName, this.dumpStack()) + // pxt.log("Validate:", off, lbl.lblName, this.dumpStack()) let currSize = this.exprStack.length - off if (lbl.lblStackSize == null) { lbl.lblStackSize = currSize } else { if (lbl.lblStackSize != currSize) { - console.log(lbl.lblStackSize, currSize) - console.log(this.dumpStack()) + pxt.log(lbl.lblStackSize, currSize) + pxt.log(this.dumpStack()) U.oops("stack misaligned at: " + lbl.lblName) } } @@ -542,7 +542,7 @@ ${baseLabel}_nochk: // result in R0 private emitExpr(e: ir.Expr): void { - //console.log(`EMITEXPR ${e.sharingInfo()} E: ${e.toString()}`) + //pxt.log(`EMITEXPR ${e.sharingInfo()} E: ${e.toString()}`) switch (e.exprKind) { case ir.EK.JmpValue: @@ -930,8 +930,8 @@ ${baseLabel}_nochk: let allArgs = nonRefs.concat(refs) for (let r of allArgs) { if (r.currUses != 0 || r.totalUses != 1) { - console.log(r.toString()) - console.log(allArgs.map(a => a.toString())) + pxt.log(r.toString()) + pxt.log(allArgs.map(a => a.toString())) U.oops(`wrong uses: ${r.currUses} ${r.totalUses}`) } r.currUses = 1 diff --git a/pxtcompiler/emitter/backjs.ts b/pxtcompiler/emitter/backjs.ts index 3f32b869104f..506a6a50c77e 100644 --- a/pxtcompiler/emitter/backjs.ts +++ b/pxtcompiler/emitter/backjs.ts @@ -455,7 +455,7 @@ function ${id}(s) { // result in R0 function emitExpr(e: ir.Expr): void { - //console.log(`EMITEXPR ${e.sharingInfo()} E: ${e.toString()}`) + //pxt.log(`EMITEXPR ${e.sharingInfo()} E: ${e.toString()}`) switch (e.exprKind) { case EK.JmpValue: @@ -607,7 +607,7 @@ function ${id}(s) { write(`${frameRef} = ${id}(s);`) } - //console.log("PROCCALL", topExpr.toString()) + //pxt.log("PROCCALL", topExpr.toString()) topExpr.args.forEach((a, i) => { let arg = `arg${i}` if (isLambda) { diff --git a/pxtcompiler/emitter/backvm.ts b/pxtcompiler/emitter/backvm.ts index 03c1caf4f703..2b06e2ac4741 100644 --- a/pxtcompiler/emitter/backvm.ts +++ b/pxtcompiler/emitter/backvm.ts @@ -370,7 +370,7 @@ _start_${name}: let keys = Object.keys(pc) keys.sort((a, b) => pc[b] - pc[a]) for (let k of keys.slice(0, 50)) { - console.log(`${k} ${pc[k]}`) + pxt.log(`${k} ${pc[k]}`) } } @@ -418,7 +418,7 @@ _start_${name}: const immMax = (1 << 23) - 1 if (pxt.options.debug) - console.log("EMIT", proc.toString()) + pxt.log("EMIT", proc.toString()) emitAll() resText = "" @@ -509,7 +509,7 @@ _start_${name}: } else { let idx = cell.index + currTmps.length - //console.log(proc.locals.length, currTmps.length, cell.index) + //pxt.log(proc.locals.length, currTmps.length, cell.index) assert(!final || idx < numLoc, "cell#" + idx) assert(idx >= 0, "cell#" + idx) return (`loc ${argDepth + idx}`) @@ -592,13 +592,13 @@ _start_${name}: case EK.SharedRef: let arg = e.args[0] if (!arg.currUses || arg.currUses >= arg.totalUses) { - console.log(arg.sharingInfo()) + pxt.log(arg.sharingInfo()) U.assert(false) } arg.currUses++ let idx = currTmps.indexOf(arg) if (idx < 0) { - console.log(currTmps, arg) + pxt.log(currTmps, arg) assert(false) } write(`ldloc ${idx + argDepth}` + (arg.currUses == arg.totalUses ? " ; LAST" : "")) @@ -618,7 +618,7 @@ _start_${name}: // result in R0 function emitExpr(e: ir.Expr): void { - //console.log(`EMITEXPR ${e.sharingInfo()} E: ${e.toString()}`) + //pxt.log(`EMITEXPR ${e.sharingInfo()} E: ${e.toString()}`) switch (e.exprKind) { case EK.JmpValue: @@ -665,7 +665,7 @@ _start_${name}: } if (idx < 0) { if (final) { - console.log(arg, currTmps) + pxt.log(arg, currTmps) assert(false, "missed tmp") } idx = currTmps.length @@ -745,7 +745,7 @@ _start_${name}: if (calledProc && calledProc.inlineBody) { const inlined = calledProc.inlineSelf(topExpr.args) if (pxt.options.debug) { - console.log("INLINE", topExpr.toString(), "->", inlined.toString()) + pxt.log("INLINE", topExpr.toString(), "->", inlined.toString()) } return emitExpr(inlined) } diff --git a/pxtcompiler/emitter/emitter.ts b/pxtcompiler/emitter/emitter.ts index d90a671c02f6..661ba995399c 100644 --- a/pxtcompiler/emitter/emitter.ts +++ b/pxtcompiler/emitter/emitter.ts @@ -244,7 +244,7 @@ namespace ts.pxtc { } function inspect(n: Node) { - console.log(stringKind(n)) + pxt.log(stringKind(n)) } // next free error 9284 @@ -1692,7 +1692,7 @@ ${lbl}: .short 0xffff let l = lookupCell(decl) recordUse(decl) let r = l.load() - //console.log("LOADLOC", l.toString(), r.toString()) + //pxt.log("LOADLOC", l.toString(), r.toString()) return r } @@ -1750,8 +1750,8 @@ ${lbl}: .short 0xffff userError(9208, lf("'this' used outside of a method")) let inf = getFunctionInfo(meth) if (!inf.thisParameter) { - //console.log("get this param,", meth.kind, nodeKey(meth)) - //console.log("GET", meth) + //pxt.log("get this param,", meth.kind, nodeKey(meth)) + //pxt.log("GET", meth) oops("no this") } return emitLocalLoad(inf.thisParameter) @@ -3007,7 +3007,7 @@ ${lbl}: .short 0xffff }) proc.args.forEach(l => { - //console.log(l.toString(), l.info) + //pxt.log(l.toString(), l.info) if (l.isByRefLocal()) { // TODO add C++ support function to do this let tmp = ir.shared(ir.rtcall("pxtrt::mklocRef", [])) @@ -3520,7 +3520,7 @@ ${lbl}: .short 0xffff } //if (info.constantFolded) - // console.log(getDeclName(decl), getSourceFileOfNode(decl).fileName, info.constantFolded.val) + // pxt.log(getDeclName(decl), getSourceFileOfNode(decl).fileName, info.constantFolded.val) return info.constantFolded } @@ -3668,7 +3668,7 @@ ${lbl}: .short 0xffff case "numops::adds": return v0 + v1; default: - console.log(e) + pxt.log(e) return undefined; } } diff --git a/pxtcompiler/emitter/esp.ts b/pxtcompiler/emitter/esp.ts index 599a3b0c987b..c781f37265e6 100644 --- a/pxtcompiler/emitter/esp.ts +++ b/pxtcompiler/emitter/esp.ts @@ -231,7 +231,7 @@ namespace pxt.esp { res[23] = 0 // disable digest } - // console.log("reparsed\n" + parseBuffer(res).segments.map(segToString).join("\n") + "\n") + // pxt.log("reparsed\n" + parseBuffer(res).segments.map(segToString).join("\n") + "\n") return res } diff --git a/pxtcompiler/emitter/formatter.ts b/pxtcompiler/emitter/formatter.ts index c0b0b246b27d..0c1e3ad52fcf 100644 --- a/pxtcompiler/emitter/formatter.ts +++ b/pxtcompiler/emitter/formatter.ts @@ -56,7 +56,7 @@ namespace ts.pxtc { function showMsg(t: Token, msg: string) { let pos = t.pos let ctx = inputForMsg.slice(pos - 20, pos) + "<*>" + inputForMsg.slice(pos, pos + 20) - console.log(ctx.replace(/\n/g, ""), ": L ", t.lineNo, msg) + pxt.log(ctx.replace(/\n/g, ""), ": L ", t.lineNo, msg) } function infixOperatorPrecedence(kind: ts.SyntaxKind) { @@ -171,7 +171,7 @@ namespace ts.pxtc { inputForMsg = input let scanner = ts.createScanner(ts.ScriptTarget.Latest, false, ts.LanguageVariant.Standard, input, msg => { let pos = scanner.getTextPos() - console.log("scanner error", pos, msg.message) + pxt.log("scanner error", pos, msg.message) }) let tokens: Token[] = [] diff --git a/pxtcompiler/emitter/hexfile.ts b/pxtcompiler/emitter/hexfile.ts index 9be9a76df009..333441581c39 100644 --- a/pxtcompiler/emitter/hexfile.ts +++ b/pxtcompiler/emitter/hexfile.ts @@ -1005,8 +1005,8 @@ ${hexfile.hexPrelude()} if (userErrors) { //TODO - console.log(U.lf("errors in inline assembly")) - console.log(userErrors) + pxt.log(U.lf("errors in inline assembly")) + pxt.log(userErrors) throw new Error(b.errors[0].message) } else { throw new Error(b.errors[0].message) diff --git a/pxtcompiler/emitter/ir.ts b/pxtcompiler/emitter/ir.ts index 8ef3cadce060..50d2e9edc11f 100644 --- a/pxtcompiler/emitter/ir.ts +++ b/pxtcompiler/emitter/ir.ts @@ -726,7 +726,7 @@ namespace ts.pxtc.ir { switch (e.exprKind) { case EK.SharedDef: let arg = e.args[0] - //console.log(arg) + //pxt.log(arg) U.assert(arg.totalUses < 0, "arg.totalUses < 0") U.assert(arg.currUses === 0, "arg.currUses === 0") // if there is just one usage, strip the SharedDef @@ -753,7 +753,7 @@ namespace ts.pxtc.ir { } let sharedincr = (e: Expr): Expr => { - //console.log("OUTSH", e.toString()) + //pxt.log("OUTSH", e.toString()) switch (e.exprKind) { case EK.SharedDef: iterargs(e, sharedincr) @@ -774,9 +774,9 @@ namespace ts.pxtc.ir { this.body = this.body.filter(s => { if (s.expr) { - //console.log("OPT", s.expr.toString()) + //pxt.log("OPT", s.expr.toString()) s.expr = opt(refdef(s.expr)) - //console.log("INTO", s.expr.toString()) + //pxt.log("INTO", s.expr.toString()) if (s.stmtKind == ir.SK.Expr && s.expr.isPure()) return false; } @@ -790,7 +790,7 @@ namespace ts.pxtc.ir { for (let s of this.body) { if (s.expr) { - //console.log("CNT", s.expr.toString()) + //pxt.log("CNT", s.expr.toString()) s.expr = cntuses(s.expr) } @@ -875,7 +875,7 @@ namespace ts.pxtc.ir { let n = allBrkp[i + 1] s += "\n" } - console.log(s) + pxt.log(s) } } } diff --git a/pxtcompiler/emitter/service.ts b/pxtcompiler/emitter/service.ts index 28f101c16c3e..1983de04ee81 100644 --- a/pxtcompiler/emitter/service.ts +++ b/pxtcompiler/emitter/service.ts @@ -452,7 +452,7 @@ namespace ts.pxtc { if (isExported(stmt as Declaration)) { if (!stmt.symbol) { - console.warn("no symbol", stmt) + pxt.warn("no symbol", stmt) return; } let qName = getFullName(typechecker, stmt.symbol) @@ -686,9 +686,9 @@ namespace ts.pxtc.service { getNewLine() { return "\n" } getCurrentDirectory(): string { return "." } getDefaultLibFileName(options: CompilerOptions): string { return "no-default-lib.d.ts" } - log(s: string): void { console.log("LOG", s) } - trace(s: string): void { console.log("TRACE", s) } - error(s: string): void { console.error("ERROR", s) } + log(s: string): void { pxt.log("LOG", s) } + trace(s: string): void { pxt.log("TRACE", s) } + error(s: string): void { pxt.error("ERROR", s) } useCaseSensitiveFileNames(): boolean { return true } // resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; @@ -979,7 +979,7 @@ namespace ts.pxtc.service { let res = runConversionsAndCompileUsingService(); timesToMs(res); if (host.opts.target.switches.time) - console.log("DIAG-TIME", res.times) + pxt.log("DIAG-TIME", res.times) return res }, diff --git a/pxtcompiler/simpledriver.ts b/pxtcompiler/simpledriver.ts index ada8823eac8f..17cba6698094 100644 --- a/pxtcompiler/simpledriver.ts +++ b/pxtcompiler/simpledriver.ts @@ -97,19 +97,19 @@ namespace pxt { } getHexInfoAsync(extInfo: pxtc.ExtensionInfo): Promise { - //console.log(`getHexInfoAsync(${extInfo})`); + //pxt.log(`getHexInfoAsync(${extInfo})`); return Promise.resolve({ hex: ["SKIP"] }) } cacheStoreAsync(id: string, val: string): Promise { - //console.log(`cacheStoreAsync(${id}, ${val})`) + //pxt.log(`cacheStoreAsync(${id}, ${val})`) if (callbacks?.cacheSet) return callbacks.cacheSet(id, val) return Promise.resolve() } cacheGetAsync(id: string): Promise { - //console.log(`cacheGetAsync(${id})`) + //pxt.log(`cacheGetAsync(${id})`) if (callbacks?.cacheGet) return callbacks.cacheGet(id) return Promise.resolve("") @@ -125,12 +125,12 @@ namespace pxt { }) } }) - //console.log(`downloadPackageAsync(${pkg.id})`) + //pxt.log(`downloadPackageAsync(${pkg.id})`) return Promise.resolve() } resolveVersionAsync(pkg: pxt.Package): Promise { - //console.log(`resolveVersionAsync(${pkg.id})`) + //pxt.log(`resolveVersionAsync(${pkg.id})`) return Promise.resolve("*") } } diff --git a/pxtcompiler/simshim.ts b/pxtcompiler/simshim.ts index e3127c7cfe89..a52d1a1da151 100644 --- a/pxtcompiler/simshim.ts +++ b/pxtcompiler/simshim.ts @@ -203,9 +203,9 @@ namespace pxt { case SK.ClassDeclaration: return emitClassDeclaration(stmt as ts.ClassDeclaration) } - //console.log("SKIP", pxtc.stringKind(stmt)) + //pxt.log("SKIP", pxtc.stringKind(stmt)) //let mod = stmt as ts.ModuleDeclaration - //if (mod.name) console.log(mod.name.text) + //if (mod.name) pxt.log(mod.name.text) /* if (mod.name) { let sym = typechecker.getSymbolAtLocation(mod.name) diff --git a/pxteditor/editorcontroller.ts b/pxteditor/editorcontroller.ts index 0dfb717ee8a0..ca25c008e500 100644 --- a/pxteditor/editorcontroller.ts +++ b/pxteditor/editorcontroller.ts @@ -298,7 +298,7 @@ export function bindEditorMessages(getEditorAsync: () => Promise) case "setlanguagerestriction": { const msg = data as pxt.editor.EditorSetLanguageRestriction; if (msg.restriction === "no-blocks") { - console.warn("no-blocks language restriction is not supported"); + pxt.warn("no-blocks language restriction is not supported"); throw new Error("no-blocks language restriction is not supported") } return projectView.setLanguageRestrictionAsync(msg.restriction); diff --git a/pxtlib/analytics.ts b/pxtlib/analytics.ts index 21864e00e765..99546dfaadc3 100644 --- a/pxtlib/analytics.ts +++ b/pxtlib/analytics.ts @@ -44,7 +44,7 @@ namespace pxt.analytics { { const prefix = consoleTicks == ConsoleTickOptions.Short ? "" : `${new Date().toLocaleTimeString(undefined, { hour12: false })} - Tick - `; const tickInfo = `${id} ${data ? JSON.stringify(data) : ""} ${opts ? JSON.stringify(opts) : ""}`; - console.log(prefix + tickInfo); + pxt.log(prefix + tickInfo); } if (te) te(id, data, opts); diff --git a/pxtlib/browserutils.ts b/pxtlib/browserutils.ts index 2d3f79a8c8e1..5782186003bf 100644 --- a/pxtlib/browserutils.ts +++ b/pxtlib/browserutils.ts @@ -770,7 +770,7 @@ namespace pxt.BrowserUtils { let md = "..."; for (let i = 0; i < 16; ++i) md += md + Math.random(); - console.log(`adding entry ${md.length * 2} bytes`); + pxt.log(`adding entry ${md.length * 2} bytes`); return U.delay(1) .then(() => translationDbAsync()) .then(db => db.setAsync("foobar", Math.random().toString(), null, undefined, md)) @@ -847,7 +847,7 @@ namespace pxt.BrowserUtils { reject(err); return; } - console.error(new Error(`${this.name} IDBWrapper error for ${op}: ${err.message}`)); + pxt.error(new Error(`${this.name} IDBWrapper error for ${op}: ${err.message}`)); reject(err); // special case for quota exceeded if (err.name == "QuotaExceededError") { @@ -999,7 +999,7 @@ namespace pxt.BrowserUtils { } return openAsync() .catch(e => { - console.log(`db: failed to open database, try delete entire store...`) + pxt.log(`db: failed to open database, try delete entire store...`) return IDBWrapper.deleteDatabaseAsync(IndexedDbTranslationDb.dbName()) .then(() => openAsync()); }) @@ -1050,16 +1050,16 @@ namespace pxt.BrowserUtils { return this.db.setAsync(IndexedDbTranslationDb.TABLE, entry) .finally(() => scheduleStorageCleanup()) // schedule a cleanpu .catch((e) => { - console.log(`db: set failed (${e.message}), recycling...`) + pxt.log(`db: set failed (${e.message}), recycling...`) return this.clearAsync(); }); } clearAsync(): Promise { return this.db.deleteAllAsync(IndexedDbTranslationDb.TABLE) - .then(() => console.debug(`db: all clean`)) + .then(() => pxt.debug(`db: all clean`)) .catch(e => { - console.error('db: failed to delete all'); + pxt.error('db: failed to delete all'); }) } } @@ -1145,7 +1145,7 @@ namespace pxt.BrowserUtils { } return openAsync() .catch(e => { - console.log(`db: failed to open tutorial info database, try delete entire store...`) + pxt.log(`db: failed to open tutorial info database, try delete entire store...`) return pxt.BrowserUtils.IDBWrapper.deleteDatabaseAsync(TutorialInfoIndexedDb.dbName()) .then(() => openAsync()); }) @@ -1205,9 +1205,9 @@ namespace pxt.BrowserUtils { clearAsync(): Promise { return this.db.deleteAllAsync(TutorialInfoIndexedDb.TABLE) - .then(() => console.debug(`db: all clean`)) + .then(() => pxt.debug(`db: all clean`)) .catch(e => { - console.error('db: failed to delete all'); + pxt.error('db: failed to delete all'); }) } } diff --git a/pxtlib/color.ts b/pxtlib/color.ts index b702a5d0b43c..7aa61ad02d03 100644 --- a/pxtlib/color.ts +++ b/pxtlib/color.ts @@ -17,7 +17,7 @@ namespace pxt { } // We couldn't find one, so just return the original - console.warn(`Couldn't find a contrasting background for color ${color}`); + pxt.warn(`Couldn't find a contrasting background for color ${color}`); return color; } diff --git a/pxtlib/commonutil.ts b/pxtlib/commonutil.ts index 888630c5b45c..75e90504103d 100644 --- a/pxtlib/commonutil.ts +++ b/pxtlib/commonutil.ts @@ -1,5 +1,6 @@ /// /// +/// namespace ts.pxtc { export let __dummy = 42; @@ -123,8 +124,8 @@ namespace ts.pxtc.Util { _didReportLocalizationsNotSet = true; pxt.tickEvent("locale.localizationsnotset"); // pxt.reportError can't be used here because of order of file imports - // Just use console.error instead, and use an Error so stacktrace is reported - console.error(new Error("Attempted to translate a string before localizations were set")); + // Just use pxt.error instead, and use an Error so stacktrace is reported + pxt.error(new Error("Attempted to translate a string before localizations were set")); }*/ return _localizeStrings[s] || s; } @@ -196,8 +197,8 @@ namespace ts.pxtc.Util { const r: { [index: string]: string; } = {}; Object.keys(locStats).sort((a, b) => locStats[b] - locStats[a]) .forEach(k => r[k] = k); - console.log('prioritized list of strings:') - console.log(JSON.stringify(r, null, 2)); + pxt.log('prioritized list of strings:') + pxt.log(JSON.stringify(r, null, 2)); } let sForPlural = true; diff --git a/pxtlib/cpp.ts b/pxtlib/cpp.ts index 229aa2375449..c01c39ee6bbb 100644 --- a/pxtlib/cpp.ts +++ b/pxtlib/cpp.ts @@ -741,7 +741,7 @@ namespace pxt.cpp { argsFmt, value: null } - //console.log(`${ln.trim()} : ${argsFmt}`) + //pxt.log(`${ln.trim()} : ${argsFmt}`) if (currDocComment) { shimsDTS.setNs(toJs(currNs)) shimsDTS.write("") @@ -1482,7 +1482,7 @@ namespace pxt.hexloader { try { keys = JSON.parse(res || "[]") } catch (e) { // cache entry is corrupted, clear cache so that it gets rebuilt - console.error('invalid cache entry, clearing entry'); + pxt.error('invalid cache entry, clearing entry'); keys = []; } keys = keys.filter(k => k != newkey) @@ -1501,7 +1501,7 @@ namespace pxt.hexloader { try { keys = JSON.parse(res || "[]") } catch (e) { // cache entry is corrupted, clear cache so that it gets rebuilt - console.error('invalid cache entry, clearing entry'); + pxt.error('invalid cache entry, clearing entry'); return host.cacheStoreAsync(idxkey, "[]") } if (keys[0] != newkey) { @@ -1531,7 +1531,7 @@ namespace pxt.hexloader { try { cachedMeta = res ? JSON.parse(res) : null } catch (e) { // cache entry is corrupted, clear cache so that it gets rebuilt - console.log('invalid cache entry, clearing entry'); + pxt.log('invalid cache entry, clearing entry'); cachedMeta = null; } if (cachedMeta && cachedMeta.hex) { diff --git a/pxtlib/diff.ts b/pxtlib/diff.ts index a5eff360786a..600dab821b41 100644 --- a/pxtlib/diff.ts +++ b/pxtlib/diff.ts @@ -263,7 +263,7 @@ namespace pxt.diff { let aidx = 0 let oidx = 0 - // console.log(da) + // pxt.log(da) for (let l of da) { if (l[0] == "+") { aidx++ diff --git a/pxtlib/docsrender.ts b/pxtlib/docsrender.ts index 553d5f271671..ba9ea3b2e069 100644 --- a/pxtlib/docsrender.ts +++ b/pxtlib/docsrender.ts @@ -1,6 +1,7 @@ /// /// /// +/// namespace pxt.docs { // eslint-disable-next-line no-var @@ -1039,7 +1040,7 @@ ${opts.repo.name.replace(/^pxt-/, '')}=github:${opts.repo.fullName}#${opts.repo. let r = augmentDocs(a, b).trim() c = c.trim() if (r != c) { - console.log(`*** Template:\n${a}\n*** Input:\n${b}\n*** Expected:\n${c}\n*** Output:\n${r}`) + pxt.log(`*** Template:\n${a}\n*** Input:\n${b}\n*** Expected:\n${c}\n*** Output:\n${r}`) throw new Error("augment docs test fail") } } diff --git a/pxtlib/emitter/assembler.ts b/pxtlib/emitter/assembler.ts index 378b5243c9ab..6d131354c851 100644 --- a/pxtlib/emitter/assembler.ts +++ b/pxtlib/emitter/assembler.ts @@ -138,7 +138,7 @@ namespace ts.pxtc.assembler { } } if (this.ei.is32bit(this)) { - // console.log(actual + " " + v.toString()) + // pxt.log(actual + " " + v.toString()) bit32_value = v bit32_actual = actual continue @@ -152,7 +152,7 @@ namespace ts.pxtc.assembler { v = enc.encode(v) - // console.log("enc(v) = ",v) + // pxt.log("enc(v) = ",v) if (v == null) return emitErr("argument out of range or mis-aligned", actual); assert((r & v) == 0) r |= v; @@ -395,9 +395,9 @@ namespace ts.pxtc.assembler { if (mul != 1) this.directiveError(lf("multiplication not supported with saved stacks")); if (this.stackpointers.hasOwnProperty(m[1])) { - // console.log(m[1] + ": " + this.stack + " " + this.stackpointers[m[1]] + " " + m[2]) + // pxt.log(m[1] + ": " + this.stack + " " + this.stackpointers[m[1]] + " " + m[2]) v = this.ei.wordSize() * this.ei.computeStackOffset(m[1], this.stack - this.stackpointers[m[1]] + parseInt(m[2])) - // console.log(v) + // pxt.log(v) } else this.directiveError(lf("saved stack not found")) @@ -1441,7 +1441,7 @@ namespace ts.pxtc.assembler { if (b.errors.length == 0) { oops("ASMTEST: expecting error for: " + asm) } - // console.log(b.errors[0].message) + // pxt.log(b.errors[0].message) } export function tohex(n: number) { @@ -1465,7 +1465,7 @@ namespace ts.pxtc.assembler { b.disablePeepHole = true; b.emit(asm); if (b.errors.length > 0) { - console.debug(b.errors[0].message) + pxt.debug(b.errors[0].message) oops("ASMTEST: not expecting errors") } diff --git a/pxtlib/gdbserver.ts b/pxtlib/gdbserver.ts index b9b5bf9c07b2..608af007a7a5 100644 --- a/pxtlib/gdbserver.ts +++ b/pxtlib/gdbserver.ts @@ -178,7 +178,7 @@ namespace pxt { return this.sendCmdOKAsync("M" + addr.toString(16) + "," + data.length.toString(16) + ":" + U.toHex(data)) .then(r => { - console.log(r) + pxt.log(r) }) } diff --git a/pxtlib/hf2.ts b/pxtlib/hf2.ts index cb69b0dd22a0..4c6a0ccab279 100644 --- a/pxtlib/hf2.ts +++ b/pxtlib/hf2.ts @@ -195,7 +195,7 @@ namespace pxt.HF2 { io.onData = buf => { let tp = buf[0] & HF2_FLAG_MASK let len = buf[0] & 63 - //console.log(`msg tp=${tp} len=${len}`) + //pxt.log(`msg tp=${tp} len=${len}`) let frame = new Uint8Array(len) U.memcpy(frame, 0, buf, 1, len) if (tp & HF2_FLAG_SERIAL_OUT) { diff --git a/pxtlib/hwdbg.ts b/pxtlib/hwdbg.ts index d9c0def3f3e9..61ec1a07f971 100644 --- a/pxtlib/hwdbg.ts +++ b/pxtlib/hwdbg.ts @@ -41,7 +41,7 @@ namespace pxt.HWDBG { export const taggedFalse = taggedSpecialValue(2) export const taggedTrue = taggedSpecialValue(16) - export let postMessage: (msg: pxsim.DebuggerMessage) => void = msg => console.log(msg) + export let postMessage: (msg: pxsim.DebuggerMessage) => void = msg => pxt.log(msg) function clearAsync() { isHalted = false @@ -154,12 +154,12 @@ namespace pxt.HWDBG { promises.push(heapExpandAsync(vars[k]) .then((r: any) => { vars[k] = r - //console.log("set", k, "to", r, "prev", vars[k], "NOW", vars) + //pxt.log("set", k, "to", r, "prev", vars[k], "NOW", vars) })) } return Promise.all(promises) .then(() => { - //console.log("FIN", vars) + //pxt.log("FIN", vars) }) } @@ -209,7 +209,7 @@ namespace pxt.HWDBG { let bestDelta = Infinity for (let b of bb) { let delta = addr - b.binAddr - // console.log(`${b.line+1}: addr=${b.binAddr} d=${delta}`) + // pxt.log(`${b.line+1}: addr=${b.binAddr} d=${delta}`) if (delta >= 0 && delta < bestDelta) { bestDelta = delta brkMatch = b @@ -293,7 +293,7 @@ namespace pxt.HWDBG { procLookup[pdi.idx] = pdi } for (let pdi of compileRes.procDebugInfo) { - //console.log(pdi) + //pxt.log(pdi) for (let ci of pdi.calls) { callInfos[ci.addr + ""] = { from: pdi, @@ -318,7 +318,7 @@ namespace pxt.HWDBG { } export function handleMessage(msg: pxsim.DebuggerMessage) { - console.log("HWDBGMSG", msg) + pxt.log("HWDBGMSG", msg) if (msg.type != "debugger") return let stepInto = false diff --git a/pxtlib/logger.ts b/pxtlib/logger.ts new file mode 100644 index 000000000000..70ca85abdfad --- /dev/null +++ b/pxtlib/logger.ts @@ -0,0 +1,67 @@ +namespace pxt { + export interface Logger { + info(...args: any[]): void; + log(...args: any[]): void; + debug(...args: any[]): void; + error(...args: any[]): void; + warn(...args: any[]): void; + } + + class ConsoleLogger implements Logger { + info(...args: any[]): void { + if (console?.info) { + console.info.call(null, ...args); + } + } + + log(...args: any[]): void { + if (console?.log) { + console.log.call(null, ...args); + } + } + + debug(...args: any[]): void { + if (console?.debug) { + console.debug.call(null, ...args); + } + } + + error(...args: any[]): void { + if (console?.error) { + console.error.call(null, ...args); + } + } + + warn(...args: any[]): void { + if (console?.warn) { + console.warn.call(null, ...args); + } + } + } + + let logger: Logger = new ConsoleLogger(); + + export function info(...args: any[]): void { + logger.info(...args); + } + + export function log(...args: any[]): void { + logger.log(...args); + } + + export function debug(...args: any[]): void { + logger.debug(...args); + } + + export function error(...args: any[]): void { + logger.error(...args); + } + + export function warn(...args: any[]): void { + logger.warn(...args); + } + + export function setLogger(impl: Logger) { + logger = impl; + } +} \ No newline at end of file diff --git a/pxtlib/main.ts b/pxtlib/main.ts index 9dbeb7da3654..631f1b6f318e 100644 --- a/pxtlib/main.ts +++ b/pxtlib/main.ts @@ -330,37 +330,22 @@ namespace pxt { } export let options: PxtOptions = {}; - // general error reported - export let debug: (msg: any) => void = typeof console !== "undefined" && !!console.debug - ? (msg) => { - if (pxt.options.debug) - console.debug(msg); - } : () => { }; - export let log: (msg: any) => void = typeof console !== "undefined" && !!console.log - ? (msg) => { - console.log(msg); - } : () => { }; - export let reportException: (err: any, data?: Map) => void = function (e, d) { - if (console) { - console.error(e); - if (d) { - try { - // log it as object, so native object inspector can be used - console.log(d) - //pxt.log(JSON.stringify(d, null, 2)) - } catch (e) { } - } + pxt.error(e); + if (d) { + try { + // log it as object, so native object inspector can be used + pxt.error(d); + //pxt.log(JSON.stringify(d, null, 2)) + } catch (e) { } } } export let reportError: (cat: string, msg: string, data?: Map) => void = function (cat, msg, data) { - if (console) { - console.error(`${cat}: ${msg}`); - if (data) { - try { - pxt.log(JSON.stringify(data, null, 2)) - } catch (e) { } - } + pxt.error(`${cat}: ${msg}`); + if (data) { + try { + pxt.log(JSON.stringify(data, null, 2)) + } catch (e) { } } } diff --git a/pxtlib/semver.ts b/pxtlib/semver.ts index 3fd23b5968d3..fd3f4aefb836 100644 --- a/pxtlib/semver.ts +++ b/pxtlib/semver.ts @@ -128,7 +128,7 @@ namespace pxt.semver { /** * Filters and sort tags from latest to oldest (semver wize) - * @param tags + * @param tags */ export function sortLatestTags(tags: string[]): string[] { const v = tags.filter(tag => !!semver.tryParse(tag)); @@ -138,7 +138,7 @@ namespace pxt.semver { } export function test() { - console.log("Test semver") + pxt.log("Test semver") let d = [ "0.9.0", "1.0.0-0.3.7", @@ -154,11 +154,11 @@ namespace pxt.semver { for (let i = 0; i < d.length; ++i) { let p = parse(d[i]) - console.log(d[i], p) + pxt.log(d[i], p) U.assert(stringify(p) == d[i]) for (let j = 0; j < d.length; ++j) { let x = cmp(p, parse(d[j])) - console.log(d[i], d[j], x) + pxt.log(d[i], d[j], x) if (i < j) U.assert(x < 0) else if (i > j) diff --git a/pxtlib/service.ts b/pxtlib/service.ts index 198b039c5b3c..716e2319571e 100644 --- a/pxtlib/service.ts +++ b/pxtlib/service.ts @@ -509,22 +509,22 @@ namespace ts.pxtc { if (s.attributes.shim === "ENUM_GET" && s.attributes.enumName && s.attributes.blockId) { let didFail = false; if (enumsByName[s.attributes.enumName]) { - console.warn(`Enum block ${s.attributes.blockId} trying to overwrite enum ${s.attributes.enumName}`); + pxt.warn(`Enum block ${s.attributes.blockId} trying to overwrite enum ${s.attributes.enumName}`); didFail = true; } if (!s.attributes.enumMemberName) { - console.warn(`Enum block ${s.attributes.blockId} should specify enumMemberName`); + pxt.warn(`Enum block ${s.attributes.blockId} should specify enumMemberName`); didFail = true; } if (!s.attributes.enumPromptHint) { - console.warn(`Enum block ${s.attributes.blockId} should specify enumPromptHint`); + pxt.warn(`Enum block ${s.attributes.blockId} should specify enumPromptHint`); didFail = true; } if (!s.attributes.enumInitialMembers || !s.attributes.enumInitialMembers.length) { - console.warn(`Enum block ${s.attributes.blockId} should specify enumInitialMembers`); + pxt.warn(`Enum block ${s.attributes.blockId} should specify enumInitialMembers`); didFail = true; } @@ -550,7 +550,7 @@ namespace ts.pxtc { const kindNamespace = s.attributes.kindNamespace || s.attributes.blockNamespace || s.namespace; if (kindsByName[kindNamespace]) { - console.warn(`More than one block defined for kind ${kindNamespace}`); + pxt.warn(`More than one block defined for kind ${kindNamespace}`); continue; } @@ -1339,7 +1339,7 @@ namespace ts.pxtc { } } - //console.log(hexDump(buf), blk) + //pxt.log(hexDump(buf), blk) return blk } @@ -1540,7 +1540,7 @@ namespace ts.pxtc { } export function readBytesFromFile(f: BlockFile, addr: number, length: number): Uint8Array { - //console.log(`read @${addr} len=${length}`) + //pxt.log(`read @${addr} len=${length}`) let needAddr = addr >> 8 let bl: Uint8Array if (needAddr == f.currPtr) diff --git a/pxtlib/tilemap.ts b/pxtlib/tilemap.ts index e892930ddccf..74b658cb1ce0 100644 --- a/pxtlib/tilemap.ts +++ b/pxtlib/tilemap.ts @@ -1234,7 +1234,7 @@ namespace pxt { data = JSON.parse(entry.data); } catch (e) { - console.warn("could not parse json data of '" + entry.id + "'"); + pxt.warn("could not parse json data of '" + entry.id + "'"); } const anim: Animation = { diff --git a/pxtlib/util.ts b/pxtlib/util.ts index 08c18fa02a39..79ff25453cf7 100644 --- a/pxtlib/util.ts +++ b/pxtlib/util.ts @@ -1141,7 +1141,7 @@ namespace ts.pxtc.Util { return resp.json; }, e => { - console.log(`failed to load translations from ${url}`) + pxt.log(`failed to load translations from ${url}`) return undefined; }) } @@ -1371,7 +1371,7 @@ namespace ts.pxtc.Util { const pAll = U.promiseMapAllSeries(stringFiles, (file) => downloadLiveTranslationsAsync(code, file.path) .then(mergeTranslations, e => { - console.log(e.message); + pxt.log(e.message); ++errorCount; }) ); @@ -1402,7 +1402,7 @@ namespace ts.pxtc.Util { translationsCache()[translationsCacheId] = translations; } }, e => { - console.error('failed to load localizations') + pxt.error('failed to load localizations') }) .then(() => translations); } @@ -2283,14 +2283,14 @@ namespace ts.pxtc.jsonPatch.tests { ]; for (const test of tests) { - console.log(test.comment); + pxt.log(test.comment); const patches = ts.pxtc.jsonPatch.diff(test.obja, test.objb); if (deepEqual(patches, test.expected)) { - console.log("succeeded"); + pxt.log("succeeded"); } else { - console.error("FAILED"); - console.log("got", patches); - console.log("exp", test.expected); + pxt.error("FAILED"); + pxt.log("got", patches); + pxt.log("exp", test.expected); } } } @@ -2349,16 +2349,16 @@ namespace ts.pxtc.jsonPatch.tests { ]; for (const test of tests) { - console.log(test.comment); + pxt.log(test.comment); ts.pxtc.jsonPatch.patchInPlace(test.obj, test.patches); const equal = deepEqual(test.obj, test.expected); const succeeded = equal && test.validate ? test.validate(test.obj) : true; if (succeeded) { - console.log("succeeded"); + pxt.log("succeeded"); } else if (test.expected) { - console.error("FAILED"); - console.log("got", test.obj); - console.log("exp", test.expected); + pxt.error("FAILED"); + pxt.log("got", test.obj); + pxt.log("exp", test.expected); } } } diff --git a/pxtlib/webusb.ts b/pxtlib/webusb.ts index bab175de698f..6ff2d0ba9ebc 100644 --- a/pxtlib/webusb.ts +++ b/pxtlib/webusb.ts @@ -632,7 +632,7 @@ namespace pxt.usb { export function isAvailable() { if (_available === undefined) { - console.error(`checkAvailableAsync not called`) + pxt.error(`checkAvailableAsync not called`) checkAvailableAsync() } return !!_available; diff --git a/pxtpy/converter.ts b/pxtpy/converter.ts index a7ee86b2d2fa..e4a920efa48a 100644 --- a/pxtpy/converter.ts +++ b/pxtpy/converter.ts @@ -1198,7 +1198,7 @@ namespace pxt.py { return scope(f); } catch (e) { - console.log(e) + pxt.log(e) return B.mkStmt(todoComment(`conversion failed for ${(v as any).name || v.kind}`, [])); } } @@ -2935,9 +2935,9 @@ namespace pxt.py { try { lastFile = fn let tokens = pxt.py.lex(src) - //console.log(pxt.py.tokensToString(tokens)) + //pxt.log(pxt.py.tokensToString(tokens)) let res = pxt.py.parse(src, sn, tokens) - //console.log(pxt.py.dump(stmts)) + //pxt.log(pxt.py.dump(stmts)) U.pushRange(diagnostics, res.diagnostics) @@ -2951,7 +2951,7 @@ namespace pxt.py { } as any) } catch (e) { // TODO - console.log("Parse error", e) + pxt.log("Parse error", e) } } @@ -2962,9 +2962,9 @@ namespace pxt.py { for (let m of modules) { try { toTS(m) - // console.log(`after ${currIteration} - ${numUnifies}`) + // pxt.log(`after ${currIteration} - ${numUnifies}`) } catch (e) { - console.log("Conv pass error", e); + pxt.log("Conv pass error", e); } } if (numUnifies == 0) @@ -3008,7 +3008,7 @@ namespace pxt.py { .map(unpackInterval) .filter(i => !!i) as pxtc.SourceInterval[] } catch (e) { - console.log("Conv error", e); + pxt.log("Conv error", e); } } diff --git a/pxtpy/parser.ts b/pxtpy/parser.ts index 19f6913a0ac5..57f72edde00d 100644 --- a/pxtpy/parser.ts +++ b/pxtpy/parser.ts @@ -109,7 +109,7 @@ namespace pxt.py { return nextToken++ skipTokens() - // console.log(`TOK: ${tokenToString(peekToken())}`) + // pxt.log(`TOK: ${tokenToString(peekToken())}`) } // next error: see "next free error" in "converter.ts" diff --git a/pxtrunner/debugRunner.ts b/pxtrunner/debugRunner.ts index 9b14cc48c59f..fe556f82cc71 100644 --- a/pxtrunner/debugRunner.ts +++ b/pxtrunner/debugRunner.ts @@ -72,7 +72,7 @@ export class DebugRunner implements pxsim.protocol.DebugSessionHost { this.initializeWebsocket(); } catch (e) { - console.warn(`Connection to server failed, retrying in ${DebugRunner.RETRY_MS} ms`); + pxt.warn(`Connection to server failed, retrying in ${DebugRunner.RETRY_MS} ms`); } } }, DebugRunner.RETRY_MS); diff --git a/pxtrunner/runner.ts b/pxtrunner/runner.ts index a04aa6010c22..840418cd9edd 100644 --- a/pxtrunner/runner.ts +++ b/pxtrunner/runner.ts @@ -184,7 +184,7 @@ function addPackageToConfig(cfg: pxt.PackageConfig, dep: string) { if (m) { cfg.dependencies[m[1]] = m[3] || "*" } else - console.warn(`unknown package syntax ${dep}`) + pxt.warn(`unknown package syntax ${dep}`) return true; } @@ -280,7 +280,7 @@ export function initFooter(footer: HTMLElement, shareId?: string) { } export function showError(msg: string) { - console.error(msg) + pxt.error(msg) } let previousMainPackage: pxt.MainPackage = undefined; @@ -345,7 +345,7 @@ function compileAsync(hex: boolean, updateOptions?: (ops: pxtc.CompileOptions) = let resp = pxtc.compile(opts) if (resp.diagnostics && resp.diagnostics.length > 0) { resp.diagnostics.forEach(diag => { - console.error(diag.messageText) + pxt.error(diag.messageText) }) } return resp @@ -359,7 +359,7 @@ export function generateHexFileAsync(options: SimulateOptions): Promise })) .then(resp => { if (resp.diagnostics && resp.diagnostics.length > 0) { - console.error("Diagnostics", resp.diagnostics) + pxt.error("Diagnostics", resp.diagnostics) } return resp.outfiles[pxtc.BINARY_HEX]; }); @@ -372,7 +372,7 @@ export function generateVMFileAsync(options: SimulateOptions): Promise { if (options.code) opts.fileSystem[pxt.MAIN_TS] = options.code; })) .then(resp => { - console.log(resp) + pxt.log(resp) return resp }) } @@ -382,7 +382,7 @@ export async function simulateAsync(container: HTMLElement, simOptions: Simulate const { js } = builtSimJS; if (!js) { - console.error("Program failed to compile"); + pxt.error("Program failed to compile"); return undefined; } @@ -544,7 +544,7 @@ export async function buildSimJsInfo(simOptions: SimulateOptions): Promise 0) { - console.error("Diagnostics", compileResult.diagnostics); + pxt.error("Diagnostics", compileResult.diagnostics); } const res = pxtc.buildSimJsInfo(compileResult); @@ -685,7 +685,7 @@ export function startRenderServer() { ? await pxt.BrowserUtils.encodeToPngAsync(res.xml, { width, height }) : undefined; } catch (e) { - console.warn(e); + pxt.warn(e); } window.parent.postMessage({ source: "makecode", @@ -931,7 +931,7 @@ ${linkString} `; } - console.debug(`print md: ${md}`); + pxt.debug(`print md: ${md}`); const options: RenderMarkdownOptions = { print: true } @@ -958,7 +958,7 @@ async function renderDocAsync(content: HTMLElement, docid: string): Promise 0) - bresp.diagnostics.forEach(diag => console.error(diag.messageText)); + bresp.diagnostics.forEach(diag => pxt.error(diag.messageText)); if (!bresp.success) return { package: mainPkg, diff --git a/pxtservices/editorDriver.ts b/pxtservices/editorDriver.ts index 30dc13ae1544..cbd094458580 100644 --- a/pxtservices/editorDriver.ts +++ b/pxtservices/editorDriver.ts @@ -530,7 +530,7 @@ export class EditorDriver extends IframeDriver { } catch (e) { error = e; - console.error(e); + pxt.error(e); } finally { if (event.response) { diff --git a/pxtservices/iframeDriver.ts b/pxtservices/iframeDriver.ts index bef798c45622..a7185edf2cd0 100644 --- a/pxtservices/iframeDriver.ts +++ b/pxtservices/iframeDriver.ts @@ -122,7 +122,7 @@ export abstract class IframeDriver { handler(data); } catch (e) { - console.error(e); + pxt.error(e); } } } diff --git a/pxtservices/loggingService.ts b/pxtservices/loggingService.ts index 0ff438ce4aeb..5320f87cd96d 100644 --- a/pxtservices/loggingService.ts +++ b/pxtservices/loggingService.ts @@ -30,16 +30,16 @@ export const logError = (errorCode: string, message?: any, data: pxt.Map { - console.log(timestamp(), message); + pxt.log(timestamp(), message); }; export const logDebug = (message: any, data?: any) => { if (pxt.BrowserUtils.isLocalHost() || pxt.options.debug) { - console.log(timestamp(), message, data); + pxt.log(timestamp(), message, data); } }; diff --git a/pxtsim/allocator.ts b/pxtsim/allocator.ts index ff39cd7ad0fd..df3beeacdaf0 100644 --- a/pxtsim/allocator.ts +++ b/pxtsim/allocator.ts @@ -234,7 +234,7 @@ namespace pxsim { } else { let instIdx = (pinDef.target).pinInstantiationIdx; if (!(!!instPins && instPins[instIdx] !== undefined)) { - console.log(`error: parts no pin found for PinInstantiationIdx: ${instIdx}. (Is the part missing an ArgumentRole or "trackArgs=" annotations?)`); + pxt.log(`error: parts no pin found for PinInstantiationIdx: ${instIdx}. (Is the part missing an ArgumentRole or "trackArgs=" annotations?)`); return undefined; } pinTarget = instPins[instIdx]; @@ -282,13 +282,13 @@ namespace pxsim { fnNms.forEach(fnNm => { if (this.opts.fnArgs[fnNm]) this.opts.fnArgs[fnNm].forEach((targetArg: string) => { callsitesTrackedArgsHash[targetArg] = 1 }); }); let callsitesTrackedArgs: string[] = Object.keys(callsitesTrackedArgsHash); if (!(!!callsitesTrackedArgs && !!callsitesTrackedArgs.length)) { - console.log(`error: parts failed to read pin(s) from callsite for: ${fnNms}`); + pxt.log(`error: parts failed to read pin(s) from callsite for: ${fnNms}`); return undefined; } callsitesTrackedArgs.forEach(fnArgsStr => { const fnArgsSplit = fnArgsStr.split(","); if (fnArgsSplit.length != fnAlloc.argumentRoles.length) { - console.log(`error: parts mismatch between number of arguments at callsite (function name: ${fnNms}) vs number of argument roles in part definition (part: ${name}).`); + pxt.log(`error: parts mismatch between number of arguments at callsite (function name: ${fnNms}) vs number of argument roles in part definition (part: ${name}).`); return; } let instPins: PinTarget[] = []; @@ -352,7 +352,7 @@ namespace pxsim { let totalSpaceNeeded = colCounts.map(d => d.colCount).reduce((p, n) => p + n, 0); let extraSpace = totalColumnsCount - totalSpaceNeeded; if (extraSpace <= 0) { - console.log("Not enough breadboard space!"); + pxt.log("Not enough breadboard space!"); //TODO } let padding = Math.floor(extraSpace / (partsCount - 1 + 2)); @@ -474,7 +474,7 @@ namespace pxsim { return this.opts.getBBCoord(loc); }); if (!firstTopAndBot[0] || !firstTopAndBot[1]) { - console.debug(`No more available "${location}" locations!`); + pxt.debug(`No more available "${location}" locations!`); //TODO } let nearTop = visuals.findClosestCoordIdx(nearestCoord, firstTopAndBot) == 0; @@ -513,12 +513,12 @@ namespace pxsim { return location; } else if (location === "MOSI" || location === "MISO" || location === "SCK") { if (!this.opts.boardDef.spiPins) - console.debug("No SPI pin mappings found!"); + pxt.debug("No SPI pin mappings found!"); let pin = (this.opts.boardDef.spiPins)[location as string] as string; return { type: "dalboard", pin: pin }; } else if (location === "SDA" || location === "SCL") { if (!this.opts.boardDef.i2cPins) - console.debug("No I2C pin mappings found!"); + pxt.debug("No I2C pin mappings found!"); let pin = (this.opts.boardDef.i2cPins)[location as string] as string; return { type: "dalboard", pin: pin }; } else { @@ -527,7 +527,7 @@ namespace pxsim { let mbPin = location; let boardPin = this.opts.boardDef.gpioPinMap[mbPin] || mbPin; if (!boardPin) { // this pin is internal - console.debug(`unknown pin location for ${mbPin}`) + pxt.debug(`unknown pin location for ${mbPin}`) return undefined; } return { type: "dalboard", pin: boardPin }; @@ -536,7 +536,7 @@ namespace pxsim { private getBoardGroundPin(): string { let pin = this.opts.boardDef.groundPins && this.opts.boardDef.groundPins[0] || null; if (!pin) { - console.debug("No available ground pin on board!"); + pxt.debug("No available ground pin on board!"); //TODO } return pin; @@ -544,7 +544,7 @@ namespace pxsim { private getBoardThreeVoltPin(): string { let pin = this.opts.boardDef.threeVoltPins && this.opts.boardDef.threeVoltPins[0] || null; if (!pin) { - console.debug("No available 3.3V pin on board!"); + pxt.debug("No available 3.3V pin on board!"); //TODO } return pin; @@ -552,7 +552,7 @@ namespace pxsim { private getBoardFiveVoltPin(): string { let pin = this.opts.boardDef.fiveVoltPins && this.opts.boardDef.fiveVoltPins[0] || null; if (!pin) { - console.debug("No available 5V pin on board!"); + pxt.debug("No available 5V pin on board!"); //TODO } return pin; diff --git a/pxtsim/debugProtocol.ts b/pxtsim/debugProtocol.ts index 1eb899f2eaba..60ebd47804f0 100644 --- a/pxtsim/debugProtocol.ts +++ b/pxtsim/debugProtocol.ts @@ -330,7 +330,7 @@ namespace pxsim.protocol { public sendResponse(response: DebugProtocol.Response): void { if (response.seq > 0) { - console.error(`attempt to send more than one response for command ${response.command}`); + pxt.error(`attempt to send more than one response for command ${response.command}`); } else { this.send('response', response); } diff --git a/pxtsim/embed.ts b/pxtsim/embed.ts index 8a86936ece05..274daa644a9f 100644 --- a/pxtsim/embed.ts +++ b/pxtsim/embed.ts @@ -523,9 +523,9 @@ namespace pxsim { const serviceWorkerUrl = window.location.href.replace(/---simulator.*$/, "---simserviceworker"); navigator.serviceWorker.register(serviceWorkerUrl).then(function (registration) { - console.log("Simulator ServiceWorker registration successful with scope: ", registration.scope); + pxt.log("Simulator ServiceWorker registration successful with scope: ", registration.scope); }, function (err) { - console.log("Simulator ServiceWorker registration failed: ", err); + pxt.log("Simulator ServiceWorker registration failed: ", err); }); } } diff --git a/pxtsim/langsupport.ts b/pxtsim/langsupport.ts index e59b1c9a95d2..f87e0a3ee32d 100644 --- a/pxtsim/langsupport.ts +++ b/pxtsim/langsupport.ts @@ -79,7 +79,7 @@ namespace pxsim { print() { if (runtime && runtime.refCountingDebug) - console.log(`RefObject id:${this.id}`) + pxt.log(`RefObject id:${this.id}`) } // render a debug preview string @@ -144,7 +144,7 @@ namespace pxsim { print() { if (runtime && runtime.refCountingDebug) - console.log(`RefRecord id:${this.id} (${this.vtable.name})`) + pxt.log(`RefRecord id:${this.id} (${this.vtable.name})`) } } @@ -179,7 +179,7 @@ namespace pxsim { print() { if (runtime && runtime.refCountingDebug) - console.log(`RefAction id:${this.id} len:${this.fields.length}`) + pxt.log(`RefAction id:${this.id} len:${this.fields.length}`) } } @@ -269,7 +269,7 @@ namespace pxsim { r += "\n" } - console.log(r) + pxt.log(r) } @@ -283,7 +283,7 @@ namespace pxsim { csv += `${p.numstops},${p.value},${p.name},${median}\n` } processPerfCounters(csv) - // console.log(csv) + // pxt.log(csv) } } @@ -302,7 +302,7 @@ namespace pxsim { print() { if (runtime && runtime.refCountingDebug) - console.log(`RefRefLocal id:${this.id} v:${this.v}`) + pxt.log(`RefRefLocal id:${this.id} v:${this.v}`) } } @@ -342,7 +342,7 @@ namespace pxsim { print() { if (runtime && runtime.refCountingDebug) - console.log(`RefMap id:${this.id} size:${this.data.length}`) + pxt.log(`RefMap id:${this.id} size:${this.data.length}`) } toAny(): any { @@ -507,7 +507,7 @@ namespace pxsim { export function stclo(a: RefAction, idx: number, v: any) { check(0 <= idx && idx < a.fields.length) check(a.fields[idx] === null) - //console.log(`STCLO [${idx}] = ${v}`) + //pxt.log(`STCLO [${idx}] = ${v}`) a.fields[idx] = v; return a; } diff --git a/pxtsim/libgeneric.ts b/pxtsim/libgeneric.ts index 133a085543de..512a4423a212 100644 --- a/pxtsim/libgeneric.ts +++ b/pxtsim/libgeneric.ts @@ -93,7 +93,7 @@ namespace pxsim { } print() { - //console.log(`RefCollection id:${this.id} refs:${this.refcnt} len:${this.data.length} d0:${this.data[0]}`) + //pxt.log(`RefCollection id:${this.id} refs:${this.refcnt} len:${this.data.length} d0:${this.data[0]}`) } } @@ -417,7 +417,7 @@ namespace pxsim { gcIsStatic() { return this.isStatic } print() { - // console.log(`RefBuffer id:${this.id} refs:${this.refcnt} len:${this.data.length} d0:${this.data[0]}`) + // pxt.log(`RefBuffer id:${this.id} refs:${this.refcnt} len:${this.data.length} d0:${this.data[0]}`) } toDebugString(): string { diff --git a/pxtsim/logger.ts b/pxtsim/logger.ts new file mode 100644 index 000000000000..70ca85abdfad --- /dev/null +++ b/pxtsim/logger.ts @@ -0,0 +1,67 @@ +namespace pxt { + export interface Logger { + info(...args: any[]): void; + log(...args: any[]): void; + debug(...args: any[]): void; + error(...args: any[]): void; + warn(...args: any[]): void; + } + + class ConsoleLogger implements Logger { + info(...args: any[]): void { + if (console?.info) { + console.info.call(null, ...args); + } + } + + log(...args: any[]): void { + if (console?.log) { + console.log.call(null, ...args); + } + } + + debug(...args: any[]): void { + if (console?.debug) { + console.debug.call(null, ...args); + } + } + + error(...args: any[]): void { + if (console?.error) { + console.error.call(null, ...args); + } + } + + warn(...args: any[]): void { + if (console?.warn) { + console.warn.call(null, ...args); + } + } + } + + let logger: Logger = new ConsoleLogger(); + + export function info(...args: any[]): void { + logger.info(...args); + } + + export function log(...args: any[]): void { + logger.log(...args); + } + + export function debug(...args: any[]): void { + logger.debug(...args); + } + + export function error(...args: any[]): void { + logger.error(...args); + } + + export function warn(...args: any[]): void { + logger.warn(...args); + } + + export function setLogger(impl: Logger) { + logger = impl; + } +} \ No newline at end of file diff --git a/pxtsim/runtime.ts b/pxtsim/runtime.ts index 3b274aa58bde..5db83870b68e 100644 --- a/pxtsim/runtime.ts +++ b/pxtsim/runtime.ts @@ -554,7 +554,7 @@ namespace pxsim { pause: thread.pause, showNumber: (n: number) => { let cb = getResume(); - console.log("SHOW NUMBER:", n) + pxt.log("SHOW NUMBER:", n) U.nextTick(cb) } } @@ -567,9 +567,9 @@ namespace pxsim { myRT.control = { inBackground: thread.runInBackground, createBuffer: BufferMethods.createBuffer, - dmesg: (s: string) => console.log("DMESG: " + s), + dmesg: (s: string) => pxt.log("DMESG: " + s), deviceDalVersion: () => "sim", - __log: (pri: number, s: string) => console.log("LOG: " + s.trim()), + __log: (pri: number, s: string) => pxt.log("LOG: " + s.trim()), } } @@ -1435,7 +1435,7 @@ namespace pxsim { function loop(p: StackFrame) { if (__this.dead) { - console.log("Runtime terminated") + pxt.log("Runtime terminated") return } U.assert(!__this.loopLock) @@ -1462,7 +1462,7 @@ namespace pxsim { if (__this.errorHandler) __this.errorHandler(e) else { - console.error("Simulator crashed, no error handler", e.stack) + pxt.error("Simulator crashed, no error handler", e.stack) const { msg, heap } = getBreakpointMsg(p, p.lastBrkId, userGlobals) injectEnvironmentGlobals(msg, heap); msg.exceptionMessage = e.message diff --git a/pxtsim/simdriver.ts b/pxtsim/simdriver.ts index 327a6a048b3c..0dd614599c9b 100644 --- a/pxtsim/simdriver.ts +++ b/pxtsim/simdriver.ts @@ -962,7 +962,7 @@ namespace pxsim { msg = 'pause'; break; default: - console.debug('unknown command') + pxt.debug('unknown command') return; } @@ -1006,7 +1006,7 @@ namespace pxsim { private handleDebuggerMessage(msg: pxsim.DebuggerMessage) { if (msg.subtype !== "trace") { - console.log("DBG-MSG", msg.subtype, msg) + pxt.log("DBG-MSG", msg.subtype, msg) } // resolve any request @@ -1043,9 +1043,9 @@ namespace pxsim { let fi = s.funcInfo stackTrace += ` at ${fi.functionName} (${fi.fileName}:${fi.line + 1}:${fi.column + 1})\n` } - if (brk.exceptionMessage) console.error(stackTrace); + if (brk.exceptionMessage) pxt.error(stackTrace); } else { - console.error("debugger: trying to pause from " + this.state); + pxt.error("debugger: trying to pause from " + this.state); } break; } diff --git a/pxtsim/simlib.ts b/pxtsim/simlib.ts index 3b71ee77ee00..888b4a0e461b 100644 --- a/pxtsim/simlib.ts +++ b/pxtsim/simlib.ts @@ -849,7 +849,7 @@ namespace pxsim { const noteNumber = data[1] || 0; const noteFrequency = frequencyFromMidiNoteNumber(noteNumber); const velocity = data[2] || 0; - //console.log(`midi: cmd ${cmd} channel (-1) ${channel} note ${noteNumber} f ${noteFrequency} v ${velocity}`) + //pxt.log(`midi: cmd ${cmd} channel (-1) ${channel} note ${noteNumber} f ${noteFrequency} v ${velocity}`) // play drums regardless if (cmd == 8 || ((cmd == 9) && (velocity == 0))) { // with MIDI, note on with velocity zero is the same as note off diff --git a/pxtsim/visuals/boardhost.ts b/pxtsim/visuals/boardhost.ts index 6f7c5b2c4b05..0547904f8bab 100644 --- a/pxtsim/visuals/boardhost.ts +++ b/pxtsim/visuals/boardhost.ts @@ -193,7 +193,7 @@ namespace pxsim.visuals { resolve(ctx.getImageData(0, 0, cvs.width, cvs.height)); }; img.onerror = e => { - console.log(e); + pxt.log(e); resolve(undefined); } img.src = data; @@ -211,7 +211,7 @@ namespace pxsim.visuals { private getPinCoord(pin: string) { let boardCoord = this.boardView.getCoord(pin); if (!boardCoord) { - console.error(`Unable to find coord for pin: ${pin}`); + pxt.error(`Unable to find coord for pin: ${pin}`); return undefined; } return this.fromMBCoord(boardCoord); @@ -226,7 +226,7 @@ namespace pxsim.visuals { coord = this.getPinCoord(pinNm); } if (!coord) - console.debug("Unknown location: " + name) + pxt.debug("Unknown location: " + name) return coord; } public getPinStyle(loc: Loc): PinStyle { diff --git a/pxtsim/visuals/wiring.ts b/pxtsim/visuals/wiring.ts index 54e92b20f640..6187431651dc 100644 --- a/pxtsim/visuals/wiring.ts +++ b/pxtsim/visuals/wiring.ts @@ -467,7 +467,7 @@ namespace pxsim.visuals { let startLoc = this.getLocCoord(start); let endLoc = this.getLocCoord(end); if (!startLoc || !endLoc) { - console.debug(`unable to allocate wire for ${start} or ${end}`); + pxt.debug(`unable to allocate wire for ${start} or ${end}`); return undefined; } //let startStyle = this.getPinStyle(start); diff --git a/webapp/src/app.tsx b/webapp/src/app.tsx index 77948b95a86c..fbd47b242eb6 100644 --- a/webapp/src/app.tsx +++ b/webapp/src/app.tsx @@ -1929,7 +1929,7 @@ export class ProjectView })(); } catch (e) { // Failed to decompile, don't propagate exception - console.error(`Failed to resolve blockconfig for tutorial: ${header.tutorial.tutorialName}, ${e.message}. md:${blockConfig.md}`); + pxt.error(`Failed to resolve blockconfig for tutorial: ${header.tutorial.tutorialName}, ${e.message}. md:${blockConfig.md}`); } for (const block of blocks) { @@ -1961,7 +1961,7 @@ export class ProjectView blockConfig.blocks.push(entry); } catch (e) { // Failed to resolve block, don't propagate exception - console.error(`Failed to resolve blockconfig for tutorial: ${header.tutorial.tutorialName}. ${e.message}`); + pxt.error(`Failed to resolve blockconfig for tutorial: ${header.tutorial.tutorialName}. ${e.message}`); } } }; @@ -2000,7 +2000,7 @@ export class ProjectView } else if (!header.tutorial.templateCode || header.tutorial.templateLoaded) { if (header.tutorial.mergeCarryoverCode && header.tutorial.mergeHeaderId) { - console.warn(lf("Refusing to carry code between tutorials because the loaded tutorial \"{0}\" does not contain a template code block.", header.tutorial.tutorial)); + pxt.warn(lf("Refusing to carry code between tutorials because the loaded tutorial \"{0}\" does not contain a template code block.", header.tutorial.tutorial)); } return; } @@ -4141,7 +4141,7 @@ export class ProjectView getBlocks(): Blockly.Block[] { if (!this.isBlocksActive()) { - console.error("Trying to get blocks from a non-blocks editor."); + pxt.error("Trying to get blocks from a non-blocks editor."); throw new Error("Trying to get blocks from a non-blocks editor."); } @@ -4150,7 +4150,7 @@ export class ProjectView getToolboxCategories(advanced?: boolean): pxt.editor.EditorMessageGetToolboxCategoriesResponse { if (!this.isBlocksActive()) { - console.error("Trying to get blocks info from a non-blocks editor."); + pxt.error("Trying to get blocks info from a non-blocks editor."); throw new Error("Trying to get blocks info from a non-blocks editor."); } @@ -5440,7 +5440,7 @@ function initPacketIO() { }, "*") } catch (e) { // data decoding failed, ignore - console.debug(`invalid utf8 serial data`, { buf, e }) + pxt.debug(`invalid utf8 serial data`, { buf, e }) } }, (type, payload) => { @@ -5541,7 +5541,7 @@ function assembleCurrent() { } function log(v: any) { - console.log(v) + pxt.log(v) } // This is for usage from JS console @@ -5936,7 +5936,7 @@ document.addEventListener("DOMContentLoaded", async () => { const optsQuery = Util.parseQueryString(window.location.href.toLowerCase()); if (optsQuery["dbg"] == "1") - pxt.debug = console.debug; + pxt.debug = pxt.debug; pxt.options.light = optsQuery["light"] == "1" || pxt.BrowserUtils.isARM() || pxt.BrowserUtils.isIE(); if (pxt.options.light) { pxsim.U.addClass(document.body, 'light'); @@ -6078,7 +6078,7 @@ document.addEventListener("DOMContentLoaded", async () => { }) let useLang: string = undefined; if (/[&?]translate=1/.test(href) && !pxt.BrowserUtils.isIE()) { - console.log(`translation mode`); + pxt.log(`translation mode`); force = true; pxt.Util.enableLiveLocalizationUpdates(); useLang = ts.pxtc.Util.TRANSLATION_LOCALE; diff --git a/webapp/src/compiler.ts b/webapp/src/compiler.ts index 5ddaac3a06d0..c725a3be9a5c 100644 --- a/webapp/src/compiler.ts +++ b/webapp/src/compiler.ts @@ -471,7 +471,7 @@ export function workerOpAsync(op: T, ar if (pxt.appTarget.compile.switches.time) { pxt.log(`Worker perf: ${op} ${Date.now() - startTm}ms`) if (res.times) - console.log(res.times) + pxt.log(res.times) } pxt.debug("worker op done: " + op) return res @@ -679,7 +679,7 @@ async function getCachedApiInfoAsync(project: pkg.EditorPackage, bundled: pxt.Ma } catch (e) { // Don't fail if the indexeddb fails, but log it - console.log("Unable to open API info cache DB"); + pxt.log("Unable to open API info cache DB"); return null; } @@ -926,7 +926,7 @@ function upgradeFromBlocksAsync(): Promise { }; }) .catch(e => { - console.log(e) + pxt.log(e) pxt.debug("Block upgrade failed, falling back to TS"); return upgradeFromTSAsync(); }); @@ -1176,7 +1176,7 @@ class ApiInfoIndexedDb { } return openAsync() .catch(e => { - console.log(`db: failed to open api database, try delete entire store...`) + pxt.log(`db: failed to open api database, try delete entire store...`) return pxt.BrowserUtils.IDBWrapper.deleteDatabaseAsync(ApiInfoIndexedDb.dbName()) .then(() => openAsync()); }) @@ -1217,9 +1217,9 @@ class ApiInfoIndexedDb { clearAsync(): Promise { return this.db.deleteAllAsync(ApiInfoIndexedDb.TABLE) - .then(() => console.debug(`db: all clean`)) + .then(() => pxt.debug(`db: all clean`)) .catch(e => { - console.error('db: failed to delete all'); + pxt.error('db: failed to delete all'); }) } } diff --git a/webapp/src/components/tutorialValidators.tsx b/webapp/src/components/tutorialValidators.tsx index 88db012cd06c..c1a5f09a8683 100644 --- a/webapp/src/components/tutorialValidators.tsx +++ b/webapp/src/components/tutorialValidators.tsx @@ -18,7 +18,7 @@ export function GetValidator(metadata: CodeValidatorMetadata): CodeValidator { case "blocksexistvalidator": return new BlocksExistValidator(metadata.properties); default: - console.error(`Unrecognized validator: ${metadata.validatorType}`); + pxt.error(`Unrecognized validator: ${metadata.validatorType}`); return null; } } diff --git a/webapp/src/core.ts b/webapp/src/core.ts index 24fc81e8a49b..8c2d64ab534c 100644 --- a/webapp/src/core.ts +++ b/webapp/src/core.ts @@ -396,13 +396,13 @@ export function apiAsync(path: string, data?: any) { Cloud.privatePostAsync(path, data) : Cloud.privateGetAsync(path)) .then(resp => { - console.log("*") - console.log("*******", path, "--->") - console.log("*") - console.log(resp) - console.log("*") + pxt.log("*") + pxt.log("*******", path, "--->") + pxt.log("*") + pxt.log(resp) + pxt.log("*") return resp }, err => { - console.log(err.message) + pxt.log(err.message) }) } diff --git a/webapp/src/extensions.tsx b/webapp/src/extensions.tsx index 1b7330a0a092..95ae5bda8781 100644 --- a/webapp/src/extensions.tsx +++ b/webapp/src/extensions.tsx @@ -179,7 +179,7 @@ export class Extensions extends data.Component frame.contentWindow.postMessage(editorMessage, "*"); } else { - console.warn(`Attempting to post message to unloaded extesnion ${name}`); + pxt.warn(`Attempting to post message to unloaded extesnion ${name}`); } } diff --git a/webapp/src/gitjson.tsx b/webapp/src/gitjson.tsx index 6a43e0a61313..bdbb63cf8431 100644 --- a/webapp/src/gitjson.tsx +++ b/webapp/src/gitjson.tsx @@ -404,7 +404,7 @@ class GithubComponent extends data.Component { const stags = pxt.semver.sortLatestTags(tags) currv = stags[0]; } catch (e) { - console.log(e) + pxt.log(e) } const v = pxt.semver.parse(currv, "0.0.0") const vmajor = pxt.semver.parse(pxt.semver.stringify(v)); vmajor.major++; vmajor.minor = 0; vmajor.patch = 0; diff --git a/webapp/src/greenscreen.tsx b/webapp/src/greenscreen.tsx index 17db9076358a..14de87019ccb 100644 --- a/webapp/src/greenscreen.tsx +++ b/webapp/src/greenscreen.tsx @@ -64,12 +64,12 @@ export class WebCam extends data.Component { } catch (e) { pxt.debug(`greenscreen: play failed`) - console.error(e) + pxt.error(e) this.stop(); } }, err => { pxt.debug(`greenscreen: get camera failed`) - console.error(err) + pxt.error(err) this.stop(); }) } @@ -91,7 +91,7 @@ export class WebCam extends data.Component { this.setState({ devices: devices.filter(device => device.kind == "videoinput") }); }, e => { pxt.debug(`greenscreen: enumerate devices failed`) - console.error(e); + pxt.error(e); }); } } diff --git a/webapp/src/hidbridge.ts b/webapp/src/hidbridge.ts index 5f541ee56810..0956defd4f88 100644 --- a/webapp/src/hidbridge.ts +++ b/webapp/src/hidbridge.ts @@ -38,7 +38,7 @@ function onOOB(v: OOB) { if (b) { b.onOOB(v) } else { - console.error("Dropping data for " + v.result.path) + pxt.error("Dropping data for " + v.result.path) } } diff --git a/webapp/src/idbworkspace.ts b/webapp/src/idbworkspace.ts index 278106b36377..c34dfd0f388e 100644 --- a/webapp/src/idbworkspace.ts +++ b/webapp/src/idbworkspace.ts @@ -147,7 +147,7 @@ async function migratePouchAsync() { prefix = prefix || getCurrentDBPrefix(); break; default: - console.warn("Unknown database table " + table); + pxt.warn("Unknown database table " + table); continue; } diff --git a/webapp/src/monacoEditAmendments.ts b/webapp/src/monacoEditAmendments.ts index d7d54217f8cd..891085ee7ca0 100644 --- a/webapp/src/monacoEditAmendments.ts +++ b/webapp/src/monacoEditAmendments.ts @@ -78,8 +78,8 @@ function scanForEditAmendment(e: monaco.editor.IModelContentChangedEvent): EditA let textAndAmendment = change.text.split(amendmentMarker) if (textAndAmendment.length != 2) { // Useful for debugging: - // console.error("Incorrect text ammendment: ") - // console.dir(change) + // pxt.error("Incorrect text ammendment: ") + // pxt.dir(change) return null } let preText = textAndAmendment[0] @@ -87,8 +87,8 @@ function scanForEditAmendment(e: monaco.editor.IModelContentChangedEvent): EditA let amendment = pxt.U.jsonTryParse(amendmentStr) as EditAmendment if (!amendment) { // Useful for debugging: - // console.error("Incorrect text ammendment JSON: ") - // console.dir(amendmentStr) + // pxt.error("Incorrect text ammendment JSON: ") + // pxt.dir(amendmentStr) return null } return Object.assign({ diff --git a/webapp/src/onboarding.ts b/webapp/src/onboarding.ts index 50b9567d7701..58b26ed38e6e 100644 --- a/webapp/src/onboarding.ts +++ b/webapp/src/onboarding.ts @@ -59,7 +59,7 @@ export async function parseTourStepsAsync(name: string): Promise