diff --git a/src/codespaces/codeSpacesServerSelector.ts b/src/codespaces/codeSpacesServerSelector.ts index fab531fdc42..2e7ef25ae95 100644 --- a/src/codespaces/codeSpacesServerSelector.ts +++ b/src/codespaces/codeSpacesServerSelector.ts @@ -4,7 +4,7 @@ /* eslint-disable @typescript-eslint/no-use-before-define */ import { inject, injectable } from 'inversify'; -import { traceError } from '../platform/logging'; +import { logger } from '../platform/logging'; import { IJupyterServerProviderRegistry, IJupyterServerUriStorage, @@ -41,7 +41,7 @@ export class CodespacesJupyterServerSelector { try { await this.jupyterConnection.validateRemoteUri(provider); } catch (err) { - traceError(`Error in validating the Remote Uri ${provider.id}.${provider.handle}`, err); + logger.error(`Error in validating the Remote Uri ${provider.id}.${provider.handle}`, err); return; } diff --git a/src/extension.common.ts b/src/extension.common.ts index b2e29fb2d9a..bbc6e44694c 100644 --- a/src/extension.common.ts +++ b/src/extension.common.ts @@ -37,7 +37,7 @@ import { } from './platform/common/types'; import { Common } from './platform/common/utils/localize'; import { IServiceContainer, IServiceManager } from './platform/ioc/types'; -import { initializeLoggers as init, traceError } from './platform/logging'; +import { initializeLoggers as init, logger } from './platform/logging'; import { getJupyterOutputChannel } from './standalone/devTools/jupyterOutputChannel'; import { isUsingPylance } from './standalone/intellisense/notebookPythonPathService'; import { noop } from './platform/common/utils/misc'; @@ -148,7 +148,7 @@ export function handleError( notifyUser(Common.handleExtensionActivationError); // Possible logger hasn't initialized either. console.error('extension activation failed', ex); - traceError('extension activation failed', ex); + logger.error('extension activation failed', ex); sendErrorTelemetry(ex, startupDurations, stopWatch); } @@ -156,7 +156,7 @@ function notifyUser(msg: string) { try { window.showErrorMessage(msg).then(noop, noop); } catch (ex) { - traceError('failed to notify user', ex); + logger.error('failed to notify user', ex); } } diff --git a/src/extension.node.ts b/src/extension.node.ts index 652a172333a..594b908755c 100644 --- a/src/extension.node.ts +++ b/src/extension.node.ts @@ -37,7 +37,7 @@ import './platform/logging'; import { commands, env, ExtensionMode, UIKind, workspace, type OutputChannel } from 'vscode'; import { buildApi, IExtensionApi } from './standalone/api'; -import { setHomeDirectory, traceError } from './platform/logging'; +import { logger, setHomeDirectory } from './platform/logging'; import { IAsyncDisposableRegistry, IExtensionContext, IsDevMode } from './platform/common/types'; import { IServiceContainer, IServiceManager } from './platform/ioc/types'; import { sendStartupTelemetry } from './platform/telemetry/startupTelemetry'; @@ -109,7 +109,7 @@ export async function activate(context: IExtensionContext): Promise `${item.kind}:${item.id}`) .join(', ')}` @@ -120,7 +120,7 @@ export class InteractiveControllerHelper implements IInteractiveControllerHelper ); }) .catch((reason) => { - traceWarning('Failed to store kernel connection metadata', reason); + logger.warn('Failed to store kernel connection metadata', reason); }); } @@ -149,7 +149,7 @@ async function createActiveInterpreterController( const controllers = registration.addOrUpdate(metadata, [viewType]); const controller = controllers[0]; // Should only create one because only one view type registration.trackActiveInterpreterControllers(controllers); - traceInfoIfCI( + logger.ci( `Active Interpreter Controller ${controller.connection.kind}:${ controller.id } created for View ${viewType} with resource ${getDisplayPath(resource)}` diff --git a/src/interactive-window/InteractiveWindowController.ts b/src/interactive-window/InteractiveWindowController.ts index dc114af5228..263c94b5d70 100644 --- a/src/interactive-window/InteractiveWindowController.ts +++ b/src/interactive-window/InteractiveWindowController.ts @@ -9,7 +9,7 @@ import { InteractiveWindowMode, Resource } from '../platform/common/types'; import { IInteractiveControllerHelper } from './types'; import { IVSCodeNotebookController } from '../notebooks/controllers/types'; import { SystemInfoCell, getFinishConnectMessage, getStartConnectMessage } from './systemInfoCell'; -import { traceError, traceInfoIfCI, traceVerbose, traceWarning } from '../platform/logging'; +import { logger } from '../platform/logging'; import { getFilePath } from '../platform/common/platform/fs-paths'; import { SysInfoReason } from '../messageTypes'; import { IDataScienceErrorHandler } from '../kernels/errors/types'; @@ -68,12 +68,12 @@ export class InteractiveWindowController { // When restart finishes, rerun our initialization code kernel.onRestarted( async () => { - traceVerbose('Restart event handled in IW'); + logger.debug('Restart event handled in IW'); this.fileInKernel = undefined; try { await this.setFileInKernel(kernel); } catch (ex) { - traceError(`Failed to run initialization after restarting`); + logger.error(`Failed to run initialization after restarting`); } finally { this.finishSysInfoMessage(kernel, SysInfoReason.Restart); } @@ -136,26 +136,26 @@ export class InteractiveWindowController { private async setFileInKernel(kernel: IKernel): Promise { const file = this.owner; if (!file) { - traceInfoIfCI('Unable to run initialization for IW'); + logger.ci('Unable to run initialization for IW'); return; } // If in perFile mode, set only once const path = getFilePath(file); const execution = this.kernelProvider.getKernelExecution(kernel!); if (this.mode === 'perFile' && !this.fileInKernel) { - traceVerbose(`Initializing __file__ in setFileInKernel with ${file} for mode ${this.mode}`); + logger.debug(`Initializing __file__ in setFileInKernel with ${file} for mode ${this.mode}`); this.fileInKernel = file; await execution.executeHidden(`__file__ = '${path.replace(/\\/g, '\\\\')}'`); } else if ( (!this.fileInKernel || this.fileInKernel.toString() !== file.toString()) && this.mode !== 'perFile' ) { - traceVerbose(`Initializing __file__ in setFileInKernel with ${file} for mode ${this.mode}`); + logger.debug(`Initializing __file__ in setFileInKernel with ${file} for mode ${this.mode}`); // Otherwise we need to reset it every time this.fileInKernel = file; await execution.executeHidden(`__file__ = '${path.replace(/\\/g, '\\\\')}'`); } else { - traceVerbose( + logger.debug( `Not Initializing __file__ in setFileInKernel with ${path} for mode ${this.mode} currently ${this.fileInKernel}` ); } @@ -203,7 +203,7 @@ export class InteractiveWindowController { this.systemInfoCell .updateMessage(message) .catch((error) => - traceWarning(`could not update info cell with message: "${message}", error: ${error}`) + logger.warn(`could not update info cell with message: "${message}", error: ${error}`) ); } } @@ -218,7 +218,7 @@ export class InteractiveWindowController { this.systemInfoCell ?.updateMessage(message) .catch((error) => - traceWarning(`System info message was not updated: "${message}" because of error: ${error}`) + logger.warn(`System info message was not updated: "${message}" because of error: ${error}`) ); this.systemInfoCell = undefined; } @@ -230,7 +230,7 @@ export class InteractiveWindowController { this.systemInfoCell ?.updateMessage(message) .catch((error) => - traceWarning(`System info message was not updated: "${message}" because of error: ${error}`) + logger.warn(`System info message was not updated: "${message}" because of error: ${error}`) ); this.systemInfoCell = undefined; } diff --git a/src/interactive-window/commands/commandRegistry.ts b/src/interactive-window/commands/commandRegistry.ts index 91f2604742f..939558caf89 100644 --- a/src/interactive-window/commands/commandRegistry.ts +++ b/src/interactive-window/commands/commandRegistry.ts @@ -35,7 +35,7 @@ import { IExtensionSyncActivationService } from '../../platform/activation/types import { ExportFormat, IFileConverter } from '../../notebooks/export/types'; import { openAndShowNotebook } from '../../platform/common/utils/notebooks'; import { JupyterInstallError } from '../../platform/errors/jupyterInstallError'; -import { traceError, traceInfo, traceVerbose } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { generateCellsFromDocument } from '../editor-integration/cellFactory'; import { IDataScienceErrorHandler } from '../../kernels/errors/types'; import { INotebookEditorProvider } from '../../notebooks/types'; @@ -391,7 +391,7 @@ export class CommandRegistry implements IDisposable, IExtensionSyncActivationSer if (iw && iw.notebookDocument) { const kernel = this.kernelProvider.get(iw.notebookDocument); if (kernel) { - traceVerbose(`Interrupt kernel due to debug stop of IW ${uri.toString()}`); + logger.debug(`Interrupt kernel due to debug stop of IW ${uri.toString()}`); // If we have a matching iw, then stop current execution await kernel.interrupt(); } @@ -578,7 +578,7 @@ export class CommandRegistry implements IDisposable, IExtensionSyncActivationSer result = await promise(); return result; } catch (err) { - traceError('listenForErrors', err as any); + logger.error('listenForErrors', err as any); this.dataScienceErrorHandler.handleError(err).then(noop, noop); } return result; @@ -678,7 +678,7 @@ export class CommandRegistry implements IDisposable, IExtensionSyncActivationSer private async expandAllCells(uri?: Uri) { const interactiveWindow = this.interactiveWindowProvider.getInteractiveWindowWithNotebook(uri); - traceInfo(`Expanding all cells in interactive window with uri ${interactiveWindow?.notebookUri}`); + logger.info(`Expanding all cells in interactive window with uri ${interactiveWindow?.notebookUri}`); if (interactiveWindow) { await interactiveWindow.expandAllCells(); } @@ -686,7 +686,7 @@ export class CommandRegistry implements IDisposable, IExtensionSyncActivationSer private async collapseAllCells(uri?: Uri) { const interactiveWindow = this.interactiveWindowProvider.getInteractiveWindowWithNotebook(uri); - traceInfo(`Collapsing all cells in interactive window with uri ${interactiveWindow?.notebookUri}`); + logger.info(`Collapsing all cells in interactive window with uri ${interactiveWindow?.notebookUri}`); if (interactiveWindow) { await interactiveWindow.collapseAllCells(); } diff --git a/src/interactive-window/debugger/interactiveWindowDebugger.node.ts b/src/interactive-window/debugger/interactiveWindowDebugger.node.ts index f7a8c8c9924..5103d80b1eb 100644 --- a/src/interactive-window/debugger/interactiveWindowDebugger.node.ts +++ b/src/interactive-window/debugger/interactiveWindowDebugger.node.ts @@ -5,7 +5,7 @@ import type * as nbformat from '@jupyterlab/nbformat'; import { inject, injectable, named } from 'inversify'; import { DebugConfiguration, Disposable, NotebookDocument } from 'vscode'; import { IPythonApiProvider } from '../../platform/api/types'; -import { traceInfo, traceInfoIfCI, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IPlatformService } from '../../platform/common/platform/types'; import { IConfigurationService } from '../../platform/common/types'; import { DataScience } from '../../platform/common/utils/localize'; @@ -76,7 +76,7 @@ export class InteractiveWindowDebugger implements IInteractiveWindowDebugger { const notebook = kernel.notebook; const config = this.configs.get(notebook); if (config) { - traceInfo('stop debugging'); + logger.info('stop debugging'); // Tell our debug service to shutdown if possible this.debuggingActive = false; @@ -93,7 +93,7 @@ export class InteractiveWindowDebugger implements IInteractiveWindowDebugger { public async updateSourceMaps(hashes: IFileGeneratedCodes[]): Promise { // Make sure that we have an active debugging session at this point if (this.debugService.activeDebugSession && this.debuggingActive) { - traceInfoIfCI(`Sending debug request for source map`); + logger.ci(`Sending debug request for source map`); await Promise.all( hashes.map(async (fileHash) => { if (this.debuggingActive) { @@ -134,14 +134,14 @@ export class InteractiveWindowDebugger implements IInteractiveWindowDebugger { kernel: IKernel, extraConfig: Partial ) { - traceInfo('start debugging'); + logger.info('start debugging'); if (!kernel.session?.kernel) { return; } // Try to connect to this notebook const config = await this.connect(kernel, extraConfig); if (config) { - traceInfo('connected to notebook during debugging'); + logger.info('connected to notebook during debugging'); this.debuggingActive = await startCommand(config); @@ -157,9 +157,9 @@ export class InteractiveWindowDebugger implements IInteractiveWindowDebugger { telemetryName: Telemetry.InteractiveWindowDebugSetupCodeFailure }); if (importResults.some((item) => item.output_type === 'error')) { - traceWarning(`${this.debuggerPackage} not found in path.`); + logger.warn(`${this.debuggerPackage} not found in path.`); } else { - traceInfo(`import startup: ${getPlainTextOrStreamOutput(importResults)}`); + logger.info(`import startup: ${getPlainTextOrStreamOutput(importResults)}`); } // After attach initially disable debugging @@ -182,7 +182,7 @@ export class InteractiveWindowDebugger implements IInteractiveWindowDebugger { ...extraConfig }; } - traceInfo('enable debugger attach'); + logger.info('enable debugger attach'); // Append any specific debugger paths that we have await this.appendDebuggerPaths(kernel); @@ -276,7 +276,7 @@ export class InteractiveWindowDebugger implements IInteractiveWindowDebugger { } ) : []; - traceInfo(`Appending paths: ${getPlainTextOrStreamOutput(result)}`); + logger.info(`Appending paths: ${getPlainTextOrStreamOutput(result)}`); } } diff --git a/src/interactive-window/debugger/jupyter/debugCellController.ts b/src/interactive-window/debugger/jupyter/debugCellController.ts index 2d4e468c579..194707c5ee9 100644 --- a/src/interactive-window/debugger/jupyter/debugCellController.ts +++ b/src/interactive-window/debugger/jupyter/debugCellController.ts @@ -12,7 +12,7 @@ import { import { IDebuggingDelegate, IKernelDebugAdapter } from '../../../notebooks/debugger/debuggingTypes'; import { cellDebugSetup } from '../../../notebooks/debugger/helper'; import { createDeferred } from '../../../platform/common/utils/async'; -import { traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { sendTelemetryEvent } from '../../../telemetry'; import { getInteractiveCellMetadata } from '../../helpers'; @@ -34,7 +34,7 @@ export class DebugCellController implements IDebuggingDelegate { } private trace(tag: string, msg: string) { - traceVerbose(`[Debug-IW] ${tag}: ${msg}`); + logger.debug(`[Debug-IW] ${tag}: ${msg}`); } public async willSendEvent(msg: DebugProtocol.Event): Promise { diff --git a/src/interactive-window/debugger/jupyter/debuggingManager.ts b/src/interactive-window/debugger/jupyter/debuggingManager.ts index 638ff75dbb8..541199c91ca 100644 --- a/src/interactive-window/debugger/jupyter/debuggingManager.ts +++ b/src/interactive-window/debugger/jupyter/debuggingManager.ts @@ -31,7 +31,7 @@ import { IConfigurationService } from '../../../platform/common/types'; import { DataScience } from '../../../platform/common/utils/localize'; import { noop } from '../../../platform/common/utils/misc'; import { IServiceContainer } from '../../../platform/ioc/types'; -import { traceError, traceInfo, traceInfoIfCI } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import * as path from '../../../platform/vscode-path/path'; import { IFileGeneratedCodes } from '../../editor-integration/types'; import { IInteractiveWindowDebuggingManager } from '../../types'; @@ -77,7 +77,7 @@ export class InteractiveWindowDebuggingManager } public async start(notebook: NotebookDocument, cell: NotebookCell) { - traceInfoIfCI(`Starting debugging IW`); + logger.ci(`Starting debugging IW`); const ipykernelResult = await this.checkIpykernelAndPrompt(cell); if (ipykernelResult === IpykernelCheckResult.Ok) { @@ -101,7 +101,7 @@ export class InteractiveWindowDebuggingManager await this.startDebuggingConfig(config, opts); const dbgr = this.notebookToDebugger.get(doc); if (!dbgr) { - traceError('Debugger not found, could not start debugging.'); + logger.error('Debugger not found, could not start debugging.'); return; } await (dbgr as IWDebugger).ready; @@ -113,17 +113,17 @@ export class InteractiveWindowDebuggingManager const notebook = workspace.notebookDocuments.find((doc) => doc.uri.toString() === config.__notebookUri); if (!notebook || typeof config.__cellIndex !== 'number') { - traceError('Invalid debug session for debugging of IW using Jupyter Protocol'); + logger.error('Invalid debug session for debugging of IW using Jupyter Protocol'); return; } if (this.notebookInProgress.has(notebook)) { - traceInfo(`Cannot start debugging. Already debugging this notebook`); + logger.info(`Cannot start debugging. Already debugging this notebook`); return; } if (this.isDebugging(notebook)) { - traceInfo(`Cannot start debugging. Already debugging this notebook document. Toolbar should update`); + logger.info(`Cannot start debugging. Already debugging this notebook document. Toolbar should update`); return; } @@ -176,7 +176,7 @@ export class InteractiveWindowDebuggingManager // Make sure that we have an active debugging session at this point let debugSession = this.getDebugSession(notebookEditor.notebook); if (debugSession) { - traceInfoIfCI(`Sending debug request for source map`); + logger.ci(`Sending debug request for source map`); await Promise.all( hashes.map(async (fileHash) => { if (debugSession) { diff --git a/src/interactive-window/debugger/jupyter/kernelDebugAdapter.ts b/src/interactive-window/debugger/jupyter/kernelDebugAdapter.ts index 559c5a8be3c..9f13490b638 100644 --- a/src/interactive-window/debugger/jupyter/kernelDebugAdapter.ts +++ b/src/interactive-window/debugger/jupyter/kernelDebugAdapter.ts @@ -9,7 +9,7 @@ import { IDebugLocationTrackerFactory, IDumpCellResponse } from '../../../notebo import { KernelDebugAdapterBase } from '../../../notebooks/debugger/kernelDebugAdapterBase'; import { IDebugService } from '../../../platform/common/application/types'; import { IPlatformService } from '../../../platform/common/platform/types'; -import { traceError, traceInfoIfCI } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import * as path from '../../../platform/vscode-path/path'; import { InteractiveCellMetadata } from '../../editor-integration/types'; /** @@ -65,7 +65,7 @@ export class KernelDebugAdapter extends KernelDebugAdapterBase { } override handleClientMessageAsync(message: DebugProtocol.ProtocolMessage): Promise { - traceInfoIfCI(`KernelDebugAdapter::handleMessage ${JSON.stringify(message, undefined, ' ')}`); + logger.ci(`KernelDebugAdapter::handleMessage ${JSON.stringify(message, undefined, ' ')}`); if (message.type === 'request' && this.debugLocationTracker?.onWillReceiveMessage) { this.debugLocationTracker.onWillReceiveMessage(message); } @@ -111,7 +111,7 @@ export class KernelDebugAdapter extends KernelDebugAdapterBase { (a, b) => b.metadata.interactive.lineIndex - a.metadata.interactive.lineIndex ); } catch (err) { - traceError(`Failed to dump cell for ${cell.index} with code ${metadata.interactive.originalSource}`, err); + logger.error(`Failed to dump cell for ${cell.index} with code ${metadata.interactive.originalSource}`, err); } } diff --git a/src/interactive-window/debugger/jupyter/restartNotSupportedController.ts b/src/interactive-window/debugger/jupyter/restartNotSupportedController.ts index ef289f2714f..a7e51bce429 100644 --- a/src/interactive-window/debugger/jupyter/restartNotSupportedController.ts +++ b/src/interactive-window/debugger/jupyter/restartNotSupportedController.ts @@ -6,7 +6,7 @@ import { DebugProtocol } from 'vscode-debugprotocol'; import { IDebuggingDelegate } from '../../../notebooks/debugger/debuggingTypes'; import { DataScience } from '../../../platform/common/utils/localize'; import { noop } from '../../../platform/common/utils/misc'; -import { traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; /** * Implements the "restart" request. @@ -15,7 +15,7 @@ export class RestartNotSupportedController implements IDebuggingDelegate { constructor(public readonly debugCell: NotebookCell) {} private trace(tag: string, msg: string) { - traceVerbose(`[Debug-IWRestart] ${tag}: ${msg}`); + logger.debug(`[Debug-IWRestart] ${tag}: ${msg}`); } public async willSendResponse(response: DebugProtocol.Response): Promise { diff --git a/src/interactive-window/editor-integration/codeGenerator.ts b/src/interactive-window/editor-integration/codeGenerator.ts index 5b435ff0e3a..24870a2e6e2 100644 --- a/src/interactive-window/editor-integration/codeGenerator.ts +++ b/src/interactive-window/editor-integration/codeGenerator.ts @@ -13,7 +13,7 @@ import { } from 'vscode'; import { splitMultilineString } from '../../platform/common/utils'; -import { traceInfo } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IConfigurationService, IDisposableRegistry } from '../../platform/common/types'; import { uncommentMagicCommands } from './cellFactory'; import { CellMatcher } from './cellMatcher'; @@ -196,7 +196,7 @@ export class CodeGenerator implements IInteractiveWindowCodeGenerator { hasCellMarker }; - traceInfo(`Generated code for ${expectedCount} = ${runtimeFile} with ${stripped.length} lines`); + logger.info(`Generated code for ${expectedCount} = ${runtimeFile} with ${stripped.length} lines`); this.storage.store(Uri.parse(metadata.interactive.uristring), hash); return hash; } diff --git a/src/interactive-window/editor-integration/codeLensFactory.ts b/src/interactive-window/editor-integration/codeLensFactory.ts index cad430e6e89..d8287275f97 100644 --- a/src/interactive-window/editor-integration/codeLensFactory.ts +++ b/src/interactive-window/editor-integration/codeLensFactory.ts @@ -4,7 +4,7 @@ import { inject, injectable } from 'inversify'; import { CodeLens, Command, Event, EventEmitter, Range, TextDocument, workspace } from 'vscode'; -import { traceWarning, traceInfoIfCI, traceVerbose } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { ICellRange, IConfigurationService, IDisposableRegistry, Resource } from '../../platform/common/types'; import * as localize from '../../platform/common/utils/localize'; @@ -155,7 +155,7 @@ export class CodeLensFactory implements ICodeLensFactory { updated = true; // Enumerate the possible commands for the document based code lenses const commands = this.enumerateCommands(document.uri); - traceVerbose( + logger.debug( `CodeLensFactory: Generating new code lenses for version ${document.version} of document ${ document.uri } for commands ${commands.join(', ')}` @@ -173,7 +173,7 @@ export class CodeLensFactory implements ICodeLensFactory { firstCell = false; }); } else { - traceInfoIfCI( + logger.ci( `NOT Generating new code lenses for version ${document.version} of document ${document.uri} - needUpdate: ${needUpdate}, cellRanges.length: ${cache.cellRanges.length}` ); } @@ -394,7 +394,7 @@ export class CodeLensFactory implements ICodeLensFactory { ]); default: - traceWarning(`Invalid command for code lens ${commandName}`); + logger.warn(`Invalid command for code lens ${commandName}`); break; } diff --git a/src/interactive-window/editor-integration/codelensprovider.ts b/src/interactive-window/editor-integration/codelensprovider.ts index d594b00b0da..3b7cb41f5f0 100644 --- a/src/interactive-window/editor-integration/codelensprovider.ts +++ b/src/interactive-window/editor-integration/codelensprovider.ts @@ -13,7 +13,7 @@ import { noop } from '../../platform/common/utils/misc'; import { StopWatch } from '../../platform/common/utils/stopWatch'; import { IServiceContainer } from '../../platform/ioc/types'; import { sendTelemetryEvent } from '../../telemetry'; -import { traceInfoIfCI, traceVerbose } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { CodeLensCommands, EditorContexts, @@ -158,7 +158,7 @@ export class DataScienceCodeLensProvider implements IDataScienceCodeLensProvider return false; }); } else { - traceInfoIfCI( + logger.ci( `Detected debugging context because activeDebugSession is name:"${this.debugService.activeDebugSession.name}", type: "${this.debugService.activeDebugSession.type}", ` + `but fell through with debugLocation: ${JSON.stringify( debugLocation @@ -185,7 +185,7 @@ export class DataScienceCodeLensProvider implements IDataScienceCodeLensProvider return codeWatcher.getCodeLenses(); } - traceVerbose(`Creating a new watcher for document ${document.uri}`); + logger.debug(`Creating a new watcher for document ${document.uri}`); const newCodeWatcher = this.createNewCodeWatcher(document); return newCodeWatcher.getCodeLenses(); } @@ -199,7 +199,7 @@ export class DataScienceCodeLensProvider implements IDataScienceCodeLensProvider // Create a new watcher for this file if we can find a matching document const possibleDocuments = vscode.workspace.textDocuments.filter((d) => d.uri.toString() === uri.toString()); if (possibleDocuments && possibleDocuments.length > 0) { - traceVerbose(`creating new code watcher with matching document ${uri}`); + logger.debug(`creating new code watcher with matching document ${uri}`); return this.createNewCodeWatcher(possibleDocuments[0]); } diff --git a/src/interactive-window/editor-integration/codewatcher.ts b/src/interactive-window/editor-integration/codewatcher.ts index 4b75075604c..40067d2bcd8 100644 --- a/src/interactive-window/editor-integration/codewatcher.ts +++ b/src/interactive-window/editor-integration/codewatcher.ts @@ -29,7 +29,7 @@ import { Telemetry, Commands, Identifiers, InteractiveWindowView } from '../../p import { IInteractiveWindowProvider, IInteractiveWindow } from '../types'; import { CellMatcher } from './cellMatcher'; import { ICodeWatcher, ICodeLensFactory } from './types'; -import { traceDecoratorVerbose } from '../../platform/logging'; +import { debugDecorator } from '../../platform/logging'; import { TraceOptions } from '../../platform/logging/types'; import * as urlPath from '../../platform/vscode-path/resources'; import { IDataScienceErrorHandler } from '../../kernels/errors/types'; @@ -324,7 +324,7 @@ export class CodeWatcher implements ICodeWatcher { } } - @traceDecoratorVerbose('CodeWatcher::runCell', TraceOptions.BeforeCall) + @debugDecorator('CodeWatcher::runCell', TraceOptions.BeforeCall) public async runCell(range: Range): Promise { if (!window.activeTextEditor || !window.activeTextEditor.document) { return; diff --git a/src/interactive-window/editor-integration/hoverProvider.ts b/src/interactive-window/editor-integration/hoverProvider.ts index 7e1c5335b85..2f73e8dc309 100644 --- a/src/interactive-window/editor-integration/hoverProvider.ts +++ b/src/interactive-window/editor-integration/hoverProvider.ts @@ -7,7 +7,7 @@ import * as vscode from 'vscode'; import { IExtensionSyncActivationService } from '../../platform/activation/types'; import { raceCancellation } from '../../platform/common/cancellation'; import { Identifiers, InteractiveWindowView, PYTHON, Telemetry } from '../../platform/common/constants'; -import { traceError } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IDisposableRegistry } from '../../platform/common/types'; import { Delayer, raceTimeout } from '../../platform/common/utils/async'; import { StopWatch } from '../../platform/common/utils/stopWatch'; @@ -71,7 +71,7 @@ export class HoverProvider implements IExtensionSyncActivationService, vscode.Ho } } catch (exc) { // Don't let exceptions in a preExecute mess up normal operation - traceError(exc); + logger.error(exc); } } diff --git a/src/interactive-window/interactiveWindow.ts b/src/interactive-window/interactiveWindow.ts index d3e72ecc1ae..db4c272fe34 100644 --- a/src/interactive-window/interactiveWindow.ts +++ b/src/interactive-window/interactiveWindow.ts @@ -21,7 +21,7 @@ import { commands } from 'vscode'; import { Commands, MARKDOWN_LANGUAGE, PYTHON_LANGUAGE, isWebExtension } from '../platform/common/constants'; -import { traceInfo, traceInfoIfCI, traceVerbose, traceWarning } from '../platform/logging'; +import { logger } from '../platform/logging'; import { IFileSystem } from '../platform/common/platform/types'; import uuid from 'uuid/v4'; import { IConfigurationService, InteractiveWindowMode, Resource } from '../platform/common/types'; @@ -191,7 +191,7 @@ export class InteractiveWindow implements IInteractiveWindow { public async ensureInitialized() { if (!this.notebookDocument) { - traceVerbose(`Showing Interactive editor to initialize codeGenerator from notebook document`); + logger.debug(`Showing Interactive editor to initialize codeGenerator from notebook document`); await this.showInteractiveEditor(); if (!this.notebookDocument) { @@ -210,7 +210,7 @@ export class InteractiveWindow implements IInteractiveWindow { if (this.controller.controller) { this.controller.startKernel().catch(noop); } else { - traceInfo('No controller selected for Interactive Window initialization'); + logger.info('No controller selected for Interactive Window initialization'); this.controller.setInfoMessageCell(DataScience.selectKernelForEditor); } } @@ -238,7 +238,7 @@ export class InteractiveWindow implements IInteractiveWindow { } private async openNotebookDocument(): Promise { - traceVerbose(`Opening notebook document ${this.notebookUri}`); + logger.debug(`Opening notebook document ${this.notebookUri}`); return await workspace.openNotebookDocument(this.notebookUri); } @@ -256,12 +256,12 @@ export class InteractiveWindow implements IInteractiveWindow { try { await execution.appendOutput(output); } catch (err) { - traceWarning(`Could not append error message "${output}" to cell: ${err}`); + logger.warn(`Could not append error message "${output}" to cell: ${err}`); } finally { execution.end(false, notebookCell.executionSummary?.timing?.endTime); } } else { - traceInfo(`Could not append error message to cell "${output}"`); + logger.info(`Could not append error message to cell "${output}"`); } } @@ -398,7 +398,7 @@ export class InteractiveWindow implements IInteractiveWindow { if (!this.controller || !this.notebookDocument) { return false; } - traceInfoIfCI('InteractiveWindow.ts.createExecutionPromise.start'); + logger.ci('InteractiveWindow.ts.createExecutionPromise.start'); // Kick of starting kernels early. const kernelPromise = this.controller.startKernel(); const cell = await notebookCellPromise; @@ -425,17 +425,17 @@ export class InteractiveWindow implements IInteractiveWindow { ); this.interactiveWindowDebugger.enable(kernel); } - traceInfoIfCI('InteractiveWindow.ts.createExecutionPromise.kernel.executeCell'); + logger.ci('InteractiveWindow.ts.createExecutionPromise.kernel.executeCell'); const iwCellMetadata = getInteractiveCellMetadata(cell); const execution = this.kernelProvider.getKernelExecution(kernel!); success = await execution.executeCell(cell, iwCellMetadata?.generatedCode?.code).then( () => true, () => false ); - traceInfoIfCI('InteractiveWindow.ts.createExecutionPromise.kernel.executeCell.finished'); + logger.ci('InteractiveWindow.ts.createExecutionPromise.kernel.executeCell.finished'); } finally { await detachKernel(); - traceInfoIfCI('InteractiveWindow.ts.createExecutionPromise.end'); + logger.ci('InteractiveWindow.ts.createExecutionPromise.end'); } if (!success) { diff --git a/src/interactive-window/interactiveWindowProvider.ts b/src/interactive-window/interactiveWindowProvider.ts index 88b24a07e9b..2bd5966b740 100644 --- a/src/interactive-window/interactiveWindowProvider.ts +++ b/src/interactive-window/interactiveWindowProvider.ts @@ -17,7 +17,7 @@ import { workspace } from 'vscode'; -import { traceInfo, traceVerbose } from '../platform/logging'; +import { logger } from '../platform/logging'; import { IFileSystem } from '../platform/common/platform/types'; import { @@ -187,7 +187,7 @@ export class InteractiveWindowProvider implements IInteractiveWindowProvider, IE try { let initialController = await this.controllerHelper.getInitialController(resource, connection); - traceInfo( + logger.info( `Starting interactive window for resource '${getDisplayPath( resource )}' with controller '${initialController?.id}'` @@ -200,7 +200,7 @@ export class InteractiveWindowProvider implements IInteractiveWindowProvider, IE NotebookControllerAffinity.Preferred ); } - traceVerbose( + logger.debug( `Interactive Window Editor Created: ${editor.notebook.uri.toString()} with input box: ${inputUri.toString()}` ); @@ -364,7 +364,7 @@ export class InteractiveWindowProvider implements IInteractiveWindowProvider, IE } private onInteractiveWindowClosed(interactiveWindow: IInteractiveWindow) { - traceVerbose(`Closing interactive window: ${interactiveWindow.notebookUri?.toString()}`); + logger.debug(`Closing interactive window: ${interactiveWindow.notebookUri?.toString()}`); interactiveWindow.dispose(); this._windows = this._windows.filter((w) => w !== interactiveWindow); this._updateWindowCache(); diff --git a/src/interactive-window/outputs/tracebackFormatter.ts b/src/interactive-window/outputs/tracebackFormatter.ts index 016cb1dcea9..b6588535284 100644 --- a/src/interactive-window/outputs/tracebackFormatter.ts +++ b/src/interactive-window/outputs/tracebackFormatter.ts @@ -6,7 +6,7 @@ import { NotebookCell, Uri } from 'vscode'; import { ITracebackFormatter } from '../../kernels/types'; import { IGeneratedCode, IFileGeneratedCodes, IGeneratedCodeStorageFactory } from '../editor-integration/types'; import { untildify } from '../../platform/common/utils/platform'; -import { traceInfoIfCI } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { getDisplayPath, getFilePath } from '../../platform/common/platform/fs-paths'; import { IPlatformService } from '../../platform/common/platform/types'; import { stripAnsi } from '../../platform/common/utils/regexp'; @@ -76,7 +76,7 @@ export class InteractiveWindowTracebackFormatter implements ITracebackFormatter return `${prefix}${num}${suffix}\n`; }); - traceInfoIfCI(`Trace frame to match: ${traceFrame}`); + logger.ci(`Trace frame to match: ${traceFrame}`); let executionCount: number | undefined; let location: string | undefined; diff --git a/src/kernels/common/baseJupyterSessionConnection.ts b/src/kernels/common/baseJupyterSessionConnection.ts index 10e07095f09..bdeb2003e4b 100644 --- a/src/kernels/common/baseJupyterSessionConnection.ts +++ b/src/kernels/common/baseJupyterSessionConnection.ts @@ -7,7 +7,7 @@ import { CancellationToken, EventEmitter } from 'vscode'; import type { IChangedArgs } from '@jupyterlab/coreutils'; import { IDisposable } from '../../platform/common/types'; import { dispose } from '../../platform/common/utils/lifecycle'; -import { traceInfo, traceInfoIfCI, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IBaseKernelSession, IKernelSocket } from '../types'; import { KernelSocketMap } from '../kernelSocket'; @@ -138,7 +138,7 @@ export abstract class BaseJupyterSessionConnection< public async restart(): Promise { await this.session.kernel?.restart(); this.initializeKernelSocket(); - traceInfo(`Restarted ${this.session?.kernel?.id}`); + logger.info(`Restarted ${this.session?.kernel?.id}`); } private previousKernelSocketInformation?: { kernel: Kernel.IKernelConnection; @@ -192,7 +192,7 @@ export abstract class BaseJupyterSessionConnection< private onStatusChanged(_: unknown, value: Kernel.Status) { this.statusChanged.emit(value); const status = this.status; - traceInfoIfCI(`Server Status = ${status}`); + logger.ci(`Server Status = ${status}`); } private onConnectionStatusChanged(_: unknown, value: Kernel.ConnectionStatus) { this.connectionStatusChanged.emit(value); @@ -201,7 +201,7 @@ export abstract class BaseJupyterSessionConnection< this.iopubMessage.emit(value); } private onUnhandledMessage(_: unknown, value: KernelMessage.IMessage) { - traceWarning(`Unhandled message found: ${value.header.msg_type}`); + logger.warn(`Unhandled message found: ${value.header.msg_type}`); this.unhandledMessage.emit(value); } private onAnyMessage(_: unknown, value: Kernel.IAnyMessageArgs) { @@ -220,6 +220,6 @@ export abstract class BaseJupyterSessionConnection< return this.session.changeKernel(options); } private onKernelConnectionStatusHandler(_: unknown, kernelConnection: Kernel.ConnectionStatus) { - traceInfoIfCI(`Server Kernel Status = ${kernelConnection}`); + logger.ci(`Server Kernel Status = ${kernelConnection}`); } } diff --git a/src/kernels/common/helpers.ts b/src/kernels/common/helpers.ts index fdb2dcc8e5e..bad282fd2d9 100644 --- a/src/kernels/common/helpers.ts +++ b/src/kernels/common/helpers.ts @@ -7,7 +7,7 @@ import { dispose } from '../../platform/common/utils/lifecycle'; import { createDeferred, raceTimeout } from '../../platform/common/utils/async'; import { DataScience } from '../../platform/common/utils/localize'; import { noop, swallowExceptions } from '../../platform/common/utils/misc'; -import { traceVerbose, traceError, traceInfoIfCI } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { KernelProgressReporter } from '../../platform/progress/kernelProgressReporter'; import { JupyterInvalidKernelError } from '../errors/jupyterInvalidKernelError'; import { JupyterWaitForIdleError } from '../errors/jupyterWaitForIdleError'; @@ -31,13 +31,13 @@ export async function waitForIdleOnSession( disposables.push(progress); } try { - traceVerbose(`Waiting for idle on (kernel): ${session.kernel.id} -> ${session.kernel.status}`); + logger.debug(`Waiting for idle on (kernel): ${session.kernel.id} -> ${session.kernel.status}`); // When our kernel connects and gets a status message it triggers the ready promise const kernelStatus = createDeferred(); token.onCancellationRequested(() => kernelStatus.reject(new CancellationError()), undefined, disposables); const handler = (_session: Kernel.IKernelConnection, status: KernelMessage.Status) => { - traceVerbose(`Got status ${status} in waitForIdleOnSession`); + logger.debug(`Got status ${status} in waitForIdleOnSession`); if (status == 'idle') { kernelStatus.resolve(status); } @@ -62,21 +62,21 @@ export async function waitForIdleOnSession( kernelStatus.promise.catch(noop); const result = await raceTimeout(timeout, '', kernelStatus.promise, sessionDisposed.promise); if (session.isDisposed) { - traceError('Session disposed while waiting for session to be idle.'); + logger.error('Session disposed while waiting for session to be idle.'); throw new JupyterInvalidKernelError(kernelConnectionMetadata); } - traceVerbose(`Finished waiting for idle on (kernel): ${session.kernel.id} -> ${session.kernel.status}`); + logger.debug(`Finished waiting for idle on (kernel): ${session.kernel.id} -> ${session.kernel.status}`); if (result == 'idle') { return; } - traceError( + logger.error( `Shutting down after failing to wait for idle on (kernel): ${session.kernel.id} -> ${session.kernel.status}` ); throw new JupyterWaitForIdleError(kernelConnectionMetadata); } catch (ex) { - traceInfoIfCI(`Error waiting for idle`, ex); + logger.ci(`Error waiting for idle`, ex); throw ex; } finally { dispose(disposables); diff --git a/src/kernels/common/kernelSocketWrapper.ts b/src/kernels/common/kernelSocketWrapper.ts index f37644c1c47..d6dc1752ff9 100644 --- a/src/kernels/common/kernelSocketWrapper.ts +++ b/src/kernels/common/kernelSocketWrapper.ts @@ -4,7 +4,7 @@ import { EventEmitter } from 'vscode'; import * as WebSocketWS from 'ws'; import { ClassType } from '../../platform/ioc/types'; -import { traceError } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IKernelSocket } from '../types'; /* eslint-disable @typescript-eslint/no-explicit-any */ @@ -101,7 +101,7 @@ export function KernelSocketWrapper>(SuperCl this.msgChain = this.msgChain .then(() => Promise.all(this.receiveHooks.map((p) => p(args[0])))) .then(() => superHandler(event, ...args)) - .catch((e) => traceError(`Exception while handling messages: ${e}`)); + .catch((e) => logger.error(`Exception while handling messages: ${e}`)); // True value indicates there were handlers. We definitely have 'message' handlers. return true; } else { diff --git a/src/kernels/common/usedPorts.ts b/src/kernels/common/usedPorts.ts index 5375b1eab74..671ef5e2f38 100644 --- a/src/kernels/common/usedPorts.ts +++ b/src/kernels/common/usedPorts.ts @@ -10,7 +10,7 @@ import { workspace } from 'vscode'; import { DisposableStore } from '../../platform/common/utils/lifecycle'; -import { traceError } from '../../platform/logging'; +import { logger } from '../../platform/logging'; // Keeps track of all ports used by Kernels and other processes spawned by Kernels and related code export const UsedPorts = new Set(); @@ -38,7 +38,7 @@ export function ignorePortForwarding(...ports: number[]) { } } catch (ex) { // In case proposed API changes. - traceError('Failure in registering port attributes', ex); + logger.error('Failure in registering port attributes', ex); } return disposableStore; diff --git a/src/kernels/errors/kernelErrorHandler.ts b/src/kernels/errors/kernelErrorHandler.ts index e685e7901f9..4f4c6d9a393 100644 --- a/src/kernels/errors/kernelErrorHandler.ts +++ b/src/kernels/errors/kernelErrorHandler.ts @@ -9,7 +9,7 @@ import { KernelConnectionTimeoutError } from './kernelConnectionTimeoutError'; import { KernelDiedError } from './kernelDiedError'; import { KernelPortNotUsedTimeoutError } from './kernelPortNotUsedTimeoutError'; import { KernelProcessExitedError } from './kernelProcessExitedError'; -import { traceError, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IConfigurationService, Resource } from '../../platform/common/types'; import { DataScience, Common } from '../../platform/common/utils/localize'; import { sendTelemetryEvent, Telemetry } from '../../telemetry'; @@ -90,7 +90,7 @@ export abstract class DataScienceErrorHandler implements IDataScienceErrorHandle private handledErrors = new WeakSet(); private handledKernelErrors = new WeakSet(); public async handleError(err: Error): Promise { - traceWarning('DataScience Error', err); + logger.warn('DataScience Error', err); err = WrappedError.unwrap(err); if (this.handledErrors.has(err)) { return; @@ -131,7 +131,7 @@ export abstract class DataScienceErrorHandler implements IDataScienceErrorHandle public async getErrorMessageForDisplayInCell(error: Error, errorContext: KernelAction, resource: Resource) { error = WrappedError.unwrap(error); if (!isCancellationError(error)) { - traceError(`Error in execution (get message for cell)`, error); + logger.error(`Error in execution (get message for cell)`, error); } if (error instanceof KernelDeadError) { // When we get this we've already asked the user to restart the kernel, @@ -285,7 +285,7 @@ export abstract class DataScienceErrorHandler implements IDataScienceErrorHandle actionSource: KernelActionSource ): Promise { if (!isCancellationError(err)) { - traceWarning(`Kernel Error, context = ${errorContext}`, err); + logger.warn(`Kernel Error, context = ${errorContext}`, err); } err = WrappedError.unwrap(err); @@ -294,7 +294,7 @@ export abstract class DataScienceErrorHandler implements IDataScienceErrorHandle this.sendKernelTelemetry(err, errorContext, resource, 'cancelled'); return KernelInterpreterDependencyResponse.cancel; } else if (err instanceof JupyterKernelDependencyError) { - traceWarning(`Jupyter Kernel Dependency Error, reason=${err.reason}`, err); + logger.warn(`Jupyter Kernel Dependency Error, reason=${err.reason}`, err); this.sendKernelTelemetry(err, errorContext, resource, err.category); if (err.reason === KernelInterpreterDependencyResponse.uiHidden && this.kernelDependency) { // At this point we're handling the error, and if the error was initially swallowed due to diff --git a/src/kernels/execution/cellExecution.ts b/src/kernels/execution/cellExecution.ts index 61a8a83bab0..2c867405b66 100644 --- a/src/kernels/execution/cellExecution.ts +++ b/src/kernels/execution/cellExecution.ts @@ -9,7 +9,7 @@ import { CellExecutionCreator } from './cellExecutionCreator'; import { analyzeKernelErrors, createOutputWithErrorMessageForDisplay } from '../../platform/errors/errorUtils'; import { BaseError } from '../../platform/errors/types'; import { dispose } from '../../platform/common/utils/lifecycle'; -import { traceError, traceInfo, traceInfoIfCI, traceVerbose, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IDisposable } from '../../platform/common/types'; import { createDeferred } from '../../platform/common/utils/async'; import { noop } from '../../platform/common/utils/misc'; @@ -104,7 +104,7 @@ export class CellExecution implements ICellExecution, IDisposable { // If the cell is deleted, then dispose the request object. // No point keeping it alive, just chewing resources. if (e === this.cell.document) { - traceInfo( + logger.info( `Disposing request as the cell (${this.cell.index}) was deleted ${getDisplayPath( this.cell.notebook.uri )}` @@ -112,7 +112,7 @@ export class CellExecution implements ICellExecution, IDisposable { try { this.request?.dispose(); // NOSONAR } catch (e) { - traceError(`Error during cell execution dispose: ${e}`); + logger.error(`Error during cell execution dispose: ${e}`); } if (this.started && !this._completed) { this.completedDueToCancellation(); @@ -159,7 +159,7 @@ export class CellExecution implements ICellExecution, IDisposable { return; } traceCellMessage(this.cell, 'Start execution'); - traceInfoIfCI(`Cell Exec contents ${this.cell.document.getText().substring(0, 50)}...`); + logger.ci(`Cell Exec contents ${this.cell.document.getText().substring(0, 50)}...`); if (!this.canExecuteCell()) { // End state is bool | undefined not optional. Undefined == not success or failure this.execution?.end(undefined); @@ -178,7 +178,7 @@ export class CellExecution implements ICellExecution, IDisposable { if (this.started) { traceCellMessage(this.cell, 'Cell has already been started yet CellExecution.Start invoked again'); - traceError(`Cell has already been started yet CellExecution.Start invoked again ${this.cell.index}`); + logger.error(`Cell has already been started yet CellExecution.Start invoked again ${this.cell.index}`); // TODO: Send telemetry this should never happen, if it does we have problems. return this.result; } @@ -201,7 +201,7 @@ export class CellExecution implements ICellExecution, IDisposable { throw new Error('Kernel not available to resume execution'); } traceCellMessage(this.cell, 'Start resuming execution'); - traceInfoIfCI(`Cell Exec (resuming) contents ${this.cell.document.getText().substring(0, 50)}...`); + logger.ci(`Cell Exec (resuming) contents ${this.cell.document.getText().substring(0, 50)}...`); if (!this.canExecuteCell()) { this.execution?.end(undefined); this.execution = undefined; @@ -209,7 +209,7 @@ export class CellExecution implements ICellExecution, IDisposable { return; } if (this.started) { - traceError(`Cell has already been started yet CellExecution.resume invoked again ${this.cell.index}`); + logger.error(`Cell has already been started yet CellExecution.resume invoked again ${this.cell.index}`); return this.result; } this.started = true; @@ -227,7 +227,7 @@ export class CellExecution implements ICellExecution, IDisposable { }); this.cellExecutionHandler.onErrorHandlingExecuteRequestIOPubMessage( (error) => { - traceError(`Cell (index = ${this.cell.index}) execution completed with errors (2).`, error); + logger.error(`Cell (index = ${this.cell.index}) execution completed with errors (2).`, error); // If not a restart error, then tell the subscriber this.completedWithErrors(error.error); }, @@ -289,9 +289,9 @@ export class CellExecution implements ICellExecution, IDisposable { return; } if (!this.disposed && !this.cancelRequested) { - traceWarning(`Cell completed with errors`, error); + logger.warn(`Cell completed with errors`, error); } else { - traceWarning(`Cell completed with errors (${this.disposed ? 'disposed' : 'cancelled'})`); + logger.warn(`Cell completed with errors (${this.disposed ? 'disposed' : 'cancelled'})`); } traceCellMessage(this.cell, 'Completed with errors'); @@ -417,7 +417,7 @@ export class CellExecution implements ICellExecution, IDisposable { try { // At this point we're about to ACTUALLY execute some code. Fire an event to indicate that notebookCellExecutions.changeCellState(this.cell, NotebookCellExecutionState.Executing); - traceVerbose(`Cell Index:${this.cell.index} sent to kernel`); + logger.debug(`Cell Index:${this.cell.index} sent to kernel`); // For Jupyter requests, silent === don't output, while store_history === don't update execution count // https://jupyter-client.readthedocs.io/en/stable/api/client.html#jupyter_client.KernelClient.execute this.request = kernelConnection.requestExecute( @@ -434,7 +434,7 @@ export class CellExecution implements ICellExecution, IDisposable { // Don't want dangling promises. this.request.done.then(noop, noop); } catch (ex) { - traceError(`Cell execution failed without request, for cell Index ${this.cell.index}`, ex); + logger.error(`Cell execution failed without request, for cell Index ${this.cell.index}`, ex); return this.completedWithErrors(ex); } this.cellExecutionHandler = this.requestListener.registerListenerForExecution(this.cell, { @@ -444,7 +444,7 @@ export class CellExecution implements ICellExecution, IDisposable { }); this.cellExecutionHandler.onErrorHandlingExecuteRequestIOPubMessage( (error) => { - traceError(`Cell (index = ${this.cell.index}) execution completed with errors (2).`, error); + logger.error(`Cell (index = ${this.cell.index}) execution completed with errors (2).`, error); // If not a restart error, then tell the subscriber this.completedWithErrors(error.error); }, @@ -486,7 +486,7 @@ export class CellExecution implements ICellExecution, IDisposable { if (!this.disposed && !this.cancelRequested) { // @jupyterlab/services throws a `Canceled` error when the kernel is interrupted. // Or even when the kernel dies when running a cell with the code `os.kill(os.getpid(), 9)` - traceError('Error in waiting for cell to complete', ex); + logger.error('Error in waiting for cell to complete', ex); } traceCellMessage(this.cell, 'Some other execution error'); if (ex && ex instanceof Error && isCancellationError(ex, true)) { diff --git a/src/kernels/execution/cellExecutionCreator.ts b/src/kernels/execution/cellExecutionCreator.ts index 492e2ed954e..06c966099b1 100644 --- a/src/kernels/execution/cellExecutionCreator.ts +++ b/src/kernels/execution/cellExecutionCreator.ts @@ -10,7 +10,7 @@ import { NotebookCellOutputItem, TextDocument } from 'vscode'; -import { traceVerbose } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IKernelController } from '../types'; import { noop } from '../../platform/common/utils/misc'; import { getNotebookTelemetryTracker } from '../telemetry/notebookTelemetry'; @@ -67,10 +67,10 @@ export class NotebookCellExecutionWrapper implements NotebookCellExecution { // indicating the fact that the kernel has started processing the output. // That's when we clear the output. (ideally it should be cleared as soon as its queued, but thats an upstream core issue). if (this.clearOutputOnStartWithTime) { - traceVerbose(`Start cell ${this.cell.index} execution @ ${startTime} (clear output)`); + logger.debug(`Start cell ${this.cell.index} execution @ ${startTime} (clear output)`); this._impl.clearOutput().then(noop, noop); } else { - traceVerbose(`Start cell ${this.cell.index} execution @ ${startTime}`); + logger.debug(`Start cell ${this.cell.index} execution @ ${startTime}`); } } } @@ -78,7 +78,7 @@ export class NotebookCellExecutionWrapper implements NotebookCellExecution { if (this._endCallback) { try { this._impl.end(success, endTime, this.errorInfo); - traceVerbose( + logger.debug( `Cell ${this.cell.index} completed in ${ ((endTime || 0) - (this._startTime || 0)) / 1000 }s (start: ${this._startTime}, end: ${endTime})` diff --git a/src/kernels/execution/cellExecutionMessageHandler.ts b/src/kernels/execution/cellExecutionMessageHandler.ts index c9400223c7a..a1d541c3642 100644 --- a/src/kernels/execution/cellExecutionMessageHandler.ts +++ b/src/kernels/execution/cellExecutionMessageHandler.ts @@ -27,7 +27,7 @@ import { import type { Kernel } from '@jupyterlab/services'; import { CellExecutionCreator } from './cellExecutionCreator'; import { dispose } from '../../platform/common/utils/lifecycle'; -import { traceError, traceInfoIfCI, traceVerbose, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IDisposable, IExtensionContext } from '../../platform/common/types'; import { concatMultilineString, formatStreamText, isJupyterNotebook } from '../../platform/common/utils'; import { @@ -416,7 +416,7 @@ export class CellExecutionMessageHandler implements IDisposable { try { this.handleIOPub(msg); } catch (ex) { - traceError(`Failed to handle iopub message as a result of some comm message`, msg, ex); + logger.error(`Failed to handle iopub message as a result of some comm message`, msg, ex); if (!this.completedExecution && !this.cell.document.isClosed) { // If there are problems handling the execution, then bubble those to the calling code. // Else just log the errors. @@ -487,7 +487,7 @@ export class CellExecutionMessageHandler implements IDisposable { // // // } this.execution?.start(this.startTime); - traceVerbose(`Kernel acknowledged execution of cell ${this.cell.index} @ ${this.startTime}`); + logger.debug(`Kernel acknowledged execution of cell ${this.cell.index} @ ${this.startTime}`); } // eslint-disable-next-line @typescript-eslint/no-require-imports @@ -520,7 +520,7 @@ export class CellExecutionMessageHandler implements IDisposable { } else if (jupyterLab.KernelMessage.isCommCloseMsg(msg)) { // Noop. } else { - traceWarning(`Unknown message ${msg.header.msg_type} : hasData=${'data' in msg.content}`); + logger.warn(`Unknown message ${msg.header.msg_type} : hasData=${'data' in msg.content}`); } // Set execution count, all messages should have it @@ -585,10 +585,10 @@ export class CellExecutionMessageHandler implements IDisposable { const IPY_MODEL_PREFIX = 'IPY_MODEL_'; data.state.children.forEach((item) => { if (typeof item !== 'string') { - return traceWarning(`Came across a comm update message a child that isn't a string`, item); + return logger.warn(`Came across a comm update message a child that isn't a string`, item); } if (!item.startsWith(IPY_MODEL_PREFIX)) { - return traceWarning( + return logger.warn( `Came across a comm update message a child that start start with ${IPY_MODEL_PREFIX}`, item ); @@ -758,7 +758,7 @@ export class CellExecutionMessageHandler implements IDisposable { .getCells() .find((cell) => CellExecutionMessageHandler.modelIdsOwnedByCells.get(cell)?.has(expectedModelId)); if (!cell) { - traceWarning(`Unable to find a cell that owns the model ${expectedModelId}`); + logger.warn(`Unable to find a cell that owns the model ${expectedModelId}`); return; } const widgetOutput = cell.outputs.find((output) => { @@ -770,7 +770,7 @@ export class CellExecutionMessageHandler implements IDisposable { const value = JSON.parse(new TextDecoder().decode(outputItem.data)) as { model_id?: string }; return value.model_id === expectedModelId; } catch (ex) { - traceWarning(`Failed to deserialize the widget data`, ex); + logger.warn(`Failed to deserialize the widget data`, ex); } return false; }); @@ -1061,11 +1061,11 @@ export class CellExecutionMessageHandler implements IDisposable { private handleError(msg: KernelMessage.IErrorMsg) { let traceback = msg.content.traceback; - traceInfoIfCI(`Traceback for error ${traceback}`); + logger.ci(`Traceback for error ${traceback}`); this.formatters.forEach((formatter) => { traceback = formatter.format(this.cell, traceback); }); - traceInfoIfCI(`Traceback for error after formatting ${traceback}`); + logger.ci(`Traceback for error after formatting ${traceback}`); const output: nbformat.IError = { output_type: 'error', ename: msg.content.ename, @@ -1109,17 +1109,17 @@ export class CellExecutionMessageHandler implements IDisposable { private handleUpdateDisplayDataMessage(msg: KernelMessage.IUpdateDisplayDataMsg) { const displayId = msg.content.transient.display_id; if (!displayId) { - traceWarning('Update display data message received, but no display id', msg.content); + logger.warn('Update display data message received, but no display id', msg.content); return; } const outputToBeUpdated = CellOutputDisplayIdTracker.getMappedOutput(this.cell.notebook, displayId); if (!outputToBeUpdated) { // Possible this is a display Id that was created by code executed by an extension. - traceVerbose('Update display data message received, but no output found to update', msg.content); + logger.debug('Update display data message received, but no output found to update', msg.content); return; } if (outputToBeUpdated.cell.document.isClosed) { - traceWarning('Update display data message received, but output cell is closed', msg.content); + logger.warn('Update display data message received, but output cell is closed', msg.content); return; } const output = translateCellDisplayOutput( @@ -1132,7 +1132,7 @@ export class CellExecutionMessageHandler implements IDisposable { } as nbformat.IDisplayData); // If there was no output and still no output, then nothing to do. if (outputToBeUpdated.outputItems.length === 0 && newOutput.items.length === 0) { - traceVerbose('Update display data message received, but no output to update', msg.content); + logger.debug('Update display data message received, but no output to update', msg.content); return; } // Compare each output item (at the end of the day everything is serializable). @@ -1154,7 +1154,7 @@ export class CellExecutionMessageHandler implements IDisposable { } if (allAllOutputItemsSame) { // If everything is still the same, then there's nothing to update. - traceVerbose( + logger.debug( 'Update display data message received, but no output to update (data is the same)', msg.content ); diff --git a/src/kernels/execution/cellExecutionQueue.ts b/src/kernels/execution/cellExecutionQueue.ts index 22f66a0c101..baf0f2097e4 100644 --- a/src/kernels/execution/cellExecutionQueue.ts +++ b/src/kernels/execution/cellExecutionQueue.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { CancellationToken, Disposable, EventEmitter, NotebookCell } from 'vscode'; -import { traceError, traceVerbose, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { noop } from '../../platform/common/utils/misc'; import { traceCellMessage } from './helpers'; import { CellExecutionFactory } from './cellExecution'; @@ -136,7 +136,7 @@ export class CellExecutionQueue implements Disposable { */ public async cancel(forced?: boolean): Promise { this.cancelledOrCompletedWithErrors = true; - traceVerbose('Cancel pending cells'); + logger.debug('Cancel pending cells'); await Promise.all(this.queueOfItemsToExecute.map((item) => item.cancel(forced))); this.lastCellExecution?.dispose(); this.queueOfItemsToExecute.splice(0, this.queueOfItemsToExecute.length); @@ -146,7 +146,7 @@ export class CellExecutionQueue implements Disposable { */ private async cancelQueuedCells(): Promise { this.cancelledOrCompletedWithErrors = true; - traceVerbose('Cancel pending cells'); + logger.debug('Cancel pending cells'); await Promise.all(this.queueOfCellsToExecute.map((item) => item.cancel())); if (this.lastCellExecution?.type === 'cell') { this.lastCellExecution?.dispose(); @@ -175,7 +175,7 @@ export class CellExecutionQueue implements Disposable { try { await this.executeQueuedCells(); } catch (ex) { - traceError('Failed to execute cells in CellExecutionQueue', ex); + logger.error('Failed to execute cells in CellExecutionQueue', ex); // Initialize this property first, so that external users of this class know whether it has completed. // Else its possible there was an error & then we wait (see next line) & in the mean time // user attempts to run another cell, then `this.completion` has not completed and we end up queuing a cell @@ -279,7 +279,7 @@ export class CellExecutionQueue implements Disposable { ) { // Only dealing with cells // Cancel everything and stop execution. - traceWarning(`Cancel all remaining cells due to ${reasons.join(' or ')}`); + logger.warn(`Cancel all remaining cells due to ${reasons.join(' or ')}`); await this.cancel(); break; } else if ( @@ -289,13 +289,13 @@ export class CellExecutionQueue implements Disposable { // Dealing with some cells and some code // Cancel execution of cells and // Continue with the execution of code. - traceWarning(`Cancel all remaining cells due to ${reasons.join(' or ')}`); + logger.warn(`Cancel all remaining cells due to ${reasons.join(' or ')}`); await this.cancelQueuedCells(); } else if (notebookClosed) { // Code execution failed, as its not related to a cell // there's no need to cancel anything. // Unless the notebook was closed. - traceWarning(`Cancel all remaining cells due to ${reasons.join(' or ')}`); + logger.warn(`Cancel all remaining cells due to ${reasons.join(' or ')}`); await this.cancel(); break; } @@ -303,7 +303,7 @@ export class CellExecutionQueue implements Disposable { // If the kernel is dead, then no point trying the rest. if (kernelConnection.status === 'dead' || kernelConnection.status === 'terminating') { this.cancelledOrCompletedWithErrors = true; - traceWarning(`Cancel all remaining cells due to dead kernel`); + logger.warn(`Cancel all remaining cells due to dead kernel`); await this.cancel(); break; } diff --git a/src/kernels/execution/codeExecution.ts b/src/kernels/execution/codeExecution.ts index 29d12d8876c..5f6a8bbc310 100644 --- a/src/kernels/execution/codeExecution.ts +++ b/src/kernels/execution/codeExecution.ts @@ -5,7 +5,7 @@ import type * as KernelMessage from '@jupyterlab/services/lib/kernel/messages'; import type { Kernel } from '@jupyterlab/services'; import { dispose } from '../../platform/common/utils/lifecycle'; -import { traceError, traceInfoIfCI, traceVerbose } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IDisposable } from '../../platform/common/types'; import { createDeferred } from '../../platform/common/utils/async'; import { noop } from '../../platform/common/utils/misc'; @@ -21,7 +21,7 @@ function traceExecMessage(extensionId: string, executionId: string, message: str if (extensionId === JVSC_EXTENSION_ID) { return; } - traceVerbose(`Execution Id:${executionId}. ${message}.`); + logger.debug(`Execution Id:${executionId}. ${message}.`); } const extensionIdsPerExtension = new Map(); @@ -80,7 +80,7 @@ export class CodeExecution implements ICodeExecution, IDisposable { return; } traceExecMessage(this.extensionId, this.executionId, 'Start Code execution'); - traceInfoIfCI(`Code Exec contents ${this.code.substring(0, 50)}...`); + logger.ci(`Code Exec contents ${this.code.substring(0, 50)}...`); if (!session.kernel || session.kernel.isDisposed || session.isDisposed) { this._done.reject(new SessionDisposedError()); return; @@ -92,7 +92,7 @@ export class CodeExecution implements ICodeExecution, IDisposable { this.executionId, 'Code has already been started yet CodeExecution.Start invoked again' ); - traceError(`Code has already been started yet CodeExecution.Start invoked again ${this.executionId}`); + logger.error(`Code has already been started yet CodeExecution.Start invoked again ${this.executionId}`); // TODO: Send telemetry this should never happen, if it does we have problems. return this.done; } @@ -180,7 +180,7 @@ export class CodeExecution implements ICodeExecution, IDisposable { // Don't want dangling promises. this.request.done.then(noop, noop); } catch (ex) { - traceError(`Code execution failed without request, for exec ${this.executionId}`, ex); + logger.error(`Code execution failed without request, for exec ${this.executionId}`, ex); this._completed = true; this._done.reject(ex); return; @@ -211,7 +211,7 @@ export class CodeExecution implements ICodeExecution, IDisposable { if (!this.disposed && !this.cancelRequested) { // @jupyterlab/services throws a `Canceled` error when the kernel is interrupted. // Or even when the kernel dies when running a cell with the code `os.kill(os.getpid(), 9)` - traceError(`Error in waiting for code ${this.executionId} to complete`, ex); + logger.error(`Error in waiting for code ${this.executionId} to complete`, ex); } this._done.reject(ex); } diff --git a/src/kernels/execution/helpers.ts b/src/kernels/execution/helpers.ts index 76bab49efaa..ade51cd40d7 100644 --- a/src/kernels/execution/helpers.ts +++ b/src/kernels/execution/helpers.ts @@ -10,7 +10,7 @@ import * as path from '../../platform/vscode-path/path'; import * as uriPath from '../../platform/vscode-path/resources'; import { PYTHON_LANGUAGE } from '../../platform/common/constants'; import { concatMultilineString, splitMultilineString } from '../../platform/common/utils'; -import { traceInfoIfCI, traceError, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { sendTelemetryEvent, Telemetry } from '../../telemetry'; import { createOutputWithErrorMessageForDisplay } from '../../platform/errors/errorUtils'; import { CellExecutionCreator } from './cellExecutionCreator'; @@ -106,7 +106,7 @@ export class NotebookCellStateTracker { export function traceCellMessage(cell: NotebookCell, message: string | (() => string)) { let messageToLog = typeof message === 'string' ? () => message : message; - traceInfoIfCI( + logger.ci( () => `Cell Index:${cell.index}, of document ${uriPath.basename( cell.notebook.uri @@ -155,7 +155,7 @@ export function cellOutputToVSCCellOutput(output: nbformat.IOutput): NotebookCel if (fn) { result = fn(output); } else { - traceWarning(`Unable to translate cell from ${output.output_type} to NotebookCellData for VS Code.`); + logger.warn(`Unable to translate cell from ${output.output_type} to NotebookCellData for VS Code.`); // eslint-disable-next-line @typescript-eslint/no-explicit-any result = translateDisplayDataOutput(output as any); } @@ -357,7 +357,7 @@ function convertOutputMimeToJupyterOutput(mime: string, value: Uint8Array) { return stringValue; } } catch (ex) { - traceError(`Failed to convert ${mime} output from a buffer ${typeof value}, ${value}`, ex); + logger.error(`Failed to convert ${mime} output from a buffer ${typeof value}, ${value}`, ex); return ''; } } @@ -384,7 +384,7 @@ function convertJupyterOutputToBuffer(mime: string, value: unknown): NotebookCel return NotebookCellOutputItem.text(value as string, mime); } } catch (ex) { - traceError(`Failed to convert ${mime} output to a buffer ${typeof value}, ${value}`, ex); + logger.error(`Failed to convert ${mime} output to a buffer ${typeof value}, ${value}`, ex); return NotebookCellOutputItem.text(''); } } diff --git a/src/kernels/helpers.node.ts b/src/kernels/helpers.node.ts index 63421c72c60..a1e8a619b89 100644 --- a/src/kernels/helpers.node.ts +++ b/src/kernels/helpers.node.ts @@ -5,7 +5,7 @@ import * as path from '../platform/vscode-path/path'; import type * as nbformat from '@jupyterlab/nbformat'; import { IJupyterKernelSpec, IKernelSession, isLocalConnection, KernelConnectionMetadata } from './types'; import { Uri } from 'vscode'; -import { traceError } from '../platform/logging'; +import { logger } from '../platform/logging'; import { Resource } from '../platform/common/types'; import { concatMultilineString } from '../platform/common/utils'; import { trackKernelResourceInformation } from './telemetry/helper'; @@ -52,7 +52,7 @@ export async function sendTelemetryForPythonKernelExecutable( const match = areInterpreterPathsSame(kernelConnection.interpreter.uri, Uri.file(sysExecutable)); await trackKernelResourceInformation(resource, { interpreterMatchesKernel: match }); } catch (ex) { - traceError(`Failed to compare interpreters after ${stopWatch.elapsedTime}ms`, ex); + logger.error(`Failed to compare interpreters after ${stopWatch.elapsedTime}ms`, ex); } } diff --git a/src/kernels/helpers.ts b/src/kernels/helpers.ts index 1c9c5118cd8..47ecaa462c2 100644 --- a/src/kernels/helpers.ts +++ b/src/kernels/helpers.ts @@ -15,7 +15,7 @@ import { } from './types'; import { NotebookCellOutput, Uri, workspace } from 'vscode'; import { PYTHON_LANGUAGE, Telemetry } from '../platform/common/constants'; -import { traceError, traceInfoIfCI, traceVerbose, traceWarning } from '../platform/logging'; +import { logger } from '../platform/logging'; import { getDisplayPath, getFilePath } from '../platform/common/platform/fs-paths'; import { DataScience } from '../platform/common/utils/localize'; import { getNormalizedInterpreterPath, getInterpreterHash } from '../platform/pythonEnvironments/info/interpreter'; @@ -385,7 +385,7 @@ export function getRemoteKernelSessionInformation( try { date = new Date(kernelConnection.kernelModel.lastActivityTime); } catch (ex) { - traceVerbose(`Error parsing date ${ex}`); + logger.debug(`Error parsing date ${ex}`); } } else { date = kernelConnection.kernelModel.lastActivityTime; @@ -613,7 +613,7 @@ export async function executeSilently( code: string, errorOptions?: SilentExecutionErrorOptions ): Promise { - traceVerbose( + logger.debug( `Executing silently Code (${kernelConnection.status}) = ${splitLines(code.substring(0, 100)).join('\\n')}` ); // eslint-disable-next-line @typescript-eslint/no-require-imports @@ -632,7 +632,7 @@ export async function executeSilently( const outputs: nbformat.IOutput[] = []; request.onIOPub = (msg) => { if (jupyterLab.KernelMessage.isStreamMsg(msg)) { - traceInfoIfCI(`Got io pub message (stream), ${splitLines(msg.content.text.substr(0, 100)).join('\\n')}`); + logger.ci(`Got io pub message (stream), ${splitLines(msg.content.text.substr(0, 100)).join('\\n')}`); if ( outputs.length > 0 && outputs[outputs.length - 1].output_type === 'stream' && @@ -649,7 +649,7 @@ export async function executeSilently( outputs.push(streamOutput); } } else if (jupyterLab.KernelMessage.isExecuteResultMsg(msg)) { - traceInfoIfCI(`Got io pub message (execresult)}`); + logger.ci(`Got io pub message (execresult)}`); const output: nbformat.IExecuteResult = { data: msg.content.data, execution_count: msg.content.execution_count, @@ -658,7 +658,7 @@ export async function executeSilently( }; outputs.push(output); } else if (jupyterLab.KernelMessage.isDisplayDataMsg(msg)) { - traceInfoIfCI(`Got io pub message (displaydata)}`); + logger.ci(`Got io pub message (displaydata)}`); const output: nbformat.IDisplayData = { data: msg.content.data, metadata: msg.content.metadata, @@ -666,7 +666,7 @@ export async function executeSilently( }; outputs.push(output); } else if (jupyterLab.KernelMessage.isErrorMsg(msg)) { - traceInfoIfCI( + logger.ci( `Got io pub message (error), ${msg.content.ename},${msg.content.evalue}, ${msg.content.traceback .join() .substring(0, 100)}}` @@ -675,7 +675,7 @@ export async function executeSilently( const errorMessage = `${ errorOptions.traceErrorsMessage || 'Failed to execute (silent) code against the kernel' }, \nCode = ${code}\nError details: `; - traceError( + logger.error( `${errorMessage} ${msg.content.ename},${msg.content.evalue}, ${msg.content.traceback.join()}` ); } @@ -687,7 +687,7 @@ export async function executeSilently( }; outputs.push(output); } else { - traceInfoIfCI(`Got io pub message (${msg.header.msg_type})`); + logger.ci(`Got io pub message (${msg.header.msg_type})`); } }; await request.done; @@ -699,7 +699,7 @@ export async function executeSilently( handleExecuteSilentErrors(outputs, errorOptions, codeForLogging); } - traceVerbose(`Executing silently Code (completed) = ${codeForLogging} with ${outputs.length} output(s)`); + logger.debug(`Executing silently Code (completed) = ${codeForLogging} with ${outputs.length} output(s)`); return outputs; } @@ -776,7 +776,7 @@ export function executeSilentlyAndEmitOutput( } else if (jupyterLab.KernelMessage.isExecuteInputMsg(msg) || jupyterLab.KernelMessage.isStatusMsg(msg)) { // } else { - traceWarning(`Got unexpected io pub message when executing code sillenty (${msg.header.msg_type})`); + logger.warn(`Got unexpected io pub message when executing code sillenty (${msg.header.msg_type})`); } }; return request; @@ -798,9 +798,9 @@ function handleExecuteSilentErrors( .join('\n')}`; const fullMessage = `${errorOptions.traceErrorsMessage || ''} ${codeForLogging} ${outputMessage}`; if (errorOptions.traceErrors) { - traceError(fullMessage); + logger.error(fullMessage); } else { - traceWarning(fullMessage); + logger.warn(fullMessage); } // Send telemetry if requested, no traceback for PII diff --git a/src/kernels/jupyter/connection/jupyterRemoteCachedKernelValidator.ts b/src/kernels/jupyter/connection/jupyterRemoteCachedKernelValidator.ts index 253387f21b8..f8b8915c361 100644 --- a/src/kernels/jupyter/connection/jupyterRemoteCachedKernelValidator.ts +++ b/src/kernels/jupyter/connection/jupyterRemoteCachedKernelValidator.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { inject, injectable } from 'inversify'; -import { traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { LiveRemoteKernelConnectionMetadata } from '../../types'; import { IJupyterRemoteCachedKernelValidator, @@ -31,7 +31,7 @@ export class JupyterRemoteCachedKernelValidator implements IJupyterRemoteCachedK (c) => c.extensionId === kernel.serverProviderHandle.extensionId && c.id === kernel.serverProviderHandle.id ); if (!collection) { - traceWarning( + logger.warn( `Extension ${kernel.serverProviderHandle.extensionId} may have been uninstalled for provider ${kernel.serverProviderHandle.id}, handle ${kernel.serverProviderHandle.handle}` ); return false; @@ -45,7 +45,7 @@ export class JupyterRemoteCachedKernelValidator implements IJupyterRemoteCachedK if (servers.map((s) => s.id).includes(kernel.serverProviderHandle.handle)) { return true; } else { - traceWarning( + logger.warn( `Hiding remote kernel ${kernel.id} for ${collection.id} as the remote Jupyter Server ${kernel.serverProviderHandle.extensionId}:${kernel.serverProviderHandle.id}:${kernel.serverProviderHandle.handle} is no longer available` ); // 3rd party extensions own these kernels, if these are no longer @@ -53,7 +53,7 @@ export class JupyterRemoteCachedKernelValidator implements IJupyterRemoteCachedK return false; } } catch (ex) { - traceWarning( + logger.warn( `Failed to fetch remote servers from ${kernel.serverProviderHandle.extensionId}:${kernel.serverProviderHandle.id}`, ex ); diff --git a/src/kernels/jupyter/connection/preferredRemoteKernelIdProvider.ts b/src/kernels/jupyter/connection/preferredRemoteKernelIdProvider.ts index e00e2cf7b0c..623fd06f04d 100644 --- a/src/kernels/jupyter/connection/preferredRemoteKernelIdProvider.ts +++ b/src/kernels/jupyter/connection/preferredRemoteKernelIdProvider.ts @@ -3,7 +3,7 @@ import { inject, injectable, named } from 'inversify'; import { Memento, NotebookDocument, Uri } from 'vscode'; -import { traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { getDisplayPath } from '../../../platform/common/platform/fs-paths'; import { IMemento, GLOBAL_MEMENTO, ICryptoUtils } from '../../../platform/common/types'; @@ -34,7 +34,7 @@ export class PreferredRemoteKernelIdProvider { // Not using a map as we're only going to store the last 40 items. const fileHash = await this.crypto.createHash(uri.toString()); const entry = list.find((l) => l.fileHash === fileHash); - traceVerbose(`Preferred Remote kernel for ${getDisplayPath(uri)} is ${entry?.kernelId}`); + logger.debug(`Preferred Remote kernel for ${getDisplayPath(uri)} is ${entry?.kernelId}`); return entry?.kernelId; } } @@ -64,7 +64,7 @@ export class PreferredRemoteKernelIdProvider { if (id) { requiresUpdate = true; list.push({ fileHash, kernelId: id }); - traceVerbose(`Storing Preferred remote kernel for ${getDisplayPath(uri)} is ${id}`); + logger.debug(`Storing Preferred remote kernel for ${getDisplayPath(uri)} is ${id}`); } // Prune list if too big diff --git a/src/kernels/jupyter/connection/serverUriStorage.ts b/src/kernels/jupyter/connection/serverUriStorage.ts index 121aa22bc33..413369d4bd5 100644 --- a/src/kernels/jupyter/connection/serverUriStorage.ts +++ b/src/kernels/jupyter/connection/serverUriStorage.ts @@ -4,7 +4,7 @@ import { EventEmitter, Memento, env } from 'vscode'; import { inject, injectable, named } from 'inversify'; import { IMemento, GLOBAL_MEMENTO, IDisposableRegistry } from '../../../platform/common/types'; -import { traceError, traceInfoIfCI } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { generateIdFromRemoteProvider } from '../jupyterUtils'; import { IJupyterServerUriEntry, IJupyterServerUriStorage, JupyterServerProviderHandle } from '../types'; import { noop } from '../../../platform/common/utils/misc'; @@ -94,7 +94,7 @@ export class JupyterServerUriStorage extends DisposableBase implements IJupyterS } public async add(jupyterHandle: JupyterServerProviderHandle, options?: { time: number }): Promise { this.hookupStorageEvents(); - traceInfoIfCI(`setUri: ${jupyterHandle.id}.${jupyterHandle.handle}`); + logger.ci(`setUri: ${jupyterHandle.id}.${jupyterHandle.handle}`); const entry: IJupyterServerUriEntry = { time: options?.time ?? Date.now(), displayName: '', @@ -251,7 +251,7 @@ class NewStorage { } } }) - .catch((ex) => traceError(`Failed to remove Server handle ${JSON.stringify(server)}`, ex))); + .catch((ex) => logger.error(`Failed to remove Server handle ${JSON.stringify(server)}`, ex))); } public getAll(): IJupyterServerUriEntry[] { const data = this.memento.get(this.mementoKey, []); diff --git a/src/kernels/jupyter/finder/remoteKernelFinder.ts b/src/kernels/jupyter/finder/remoteKernelFinder.ts index cbc9b12e0e4..8a262fcb70a 100644 --- a/src/kernels/jupyter/finder/remoteKernelFinder.ts +++ b/src/kernels/jupyter/finder/remoteKernelFinder.ts @@ -16,7 +16,7 @@ import { import { IAsyncDisposable, IDisposable, IExtensionContext } from '../../../platform/common/types'; import { IJupyterRemoteCachedKernelValidator, IRemoteKernelFinder, JupyterServerProviderHandle } from '../types'; import { sendKernelSpecTelemetry } from '../../raw/finder/helper'; -import { traceError, traceWarning, traceInfoIfCI, traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { raceCancellation } from '../../../platform/common/cancellation'; import { areObjectsWithUrisTheSame, noop } from '../../../platform/common/utils/misc'; import { IApplicationEnvironment } from '../../../platform/common/application/types'; @@ -198,7 +198,7 @@ export class RemoteKernelFinder extends ObservableDisposable implements IRemoteK } public async loadCache(ignoreCache: boolean = false, displayProgress: boolean = false): Promise { - traceInfoIfCI(`Remote Kernel Finder load cache Server: ${this.id}`); + logger.ci(`Remote Kernel Finder load cache Server: ${this.id}`); const promise = (async () => { const kernelsFromCache = ignoreCache ? [] : await this.getFromCache(); @@ -221,7 +221,7 @@ export class RemoteKernelFinder extends ObservableDisposable implements IRemoteK } catch (ex) { // CancellationError is when user cancels the request, no need to log errors related to that. if (!(ex instanceof CancellationError)) { - traceError('UniversalRemoteKernelFinder: Failed to get kernels without cache', ex); + logger.error('UniversalRemoteKernelFinder: Failed to get kernels without cache', ex); this._lastError = ex; this._onDidChange.fire(); } @@ -244,7 +244,7 @@ export class RemoteKernelFinder extends ObservableDisposable implements IRemoteK try { kernels = await this.getListOfKernelsWithCachedConnection(false); } catch (ex) { - traceWarning(`Could not fetch kernels from the ${this.kind} server, falling back to cache: ${ex}`); + logger.warn(`Could not fetch kernels from the ${this.kind} server, falling back to cache: ${ex}`); // Since fetching the remote kernels failed, we fall back to the cache, // at this point no need to display all of the kernel specs, // Its possible the connection is dead, just display the live kernels we had. @@ -297,7 +297,7 @@ export class RemoteKernelFinder extends ObservableDisposable implements IRemoteK await raceCancellation(cancelToken, promise); return validValues; } catch (ex) { - traceError('UniversalRemoteKernelFinder: Failed to get from cache', ex); + logger.error('UniversalRemoteKernelFinder: Failed to get from cache', ex); } return []; @@ -381,7 +381,7 @@ export class RemoteKernelFinder extends ObservableDisposable implements IRemoteK const filtered = mappedLive.filter((k) => !this.kernelIdsToHide.has(k.kernelModel.id || '')); return [...filtered, ...mappedSpecs]; } catch (ex) { - traceError(`Error fetching kernels from ${connInfo.baseUrl} (${connInfo.displayName}):`, ex); + logger.error(`Error fetching kernels from ${connInfo.baseUrl} (${connInfo.displayName}):`, ex); throw ex; } finally { await Promise.all(disposables.map((d) => d.dispose().catch(noop))); @@ -390,7 +390,7 @@ export class RemoteKernelFinder extends ObservableDisposable implements IRemoteK private async writeToCache(values: RemoteKernelConnectionMetadata[]) { try { - traceVerbose( + logger.debug( `UniversalRemoteKernelFinder: Writing ${values.length} remote kernel connection metadata to cache` ); @@ -437,7 +437,7 @@ export class RemoteKernelFinder extends ObservableDisposable implements IRemoteK .createDirectory(this.context.globalStorageUri) .then(() => this.fs.writeFile(this.cacheFile, JSON.stringify(currentData))) .catch((ex) => { - traceError(`Failed to cache the remote kernels.`, ex); + logger.error(`Failed to cache the remote kernels.`, ex); }); if (added.length || updated.length || removed.length) { @@ -445,7 +445,7 @@ export class RemoteKernelFinder extends ObservableDisposable implements IRemoteK // this._onDidChangeKernels.fire({ added, updated, removed }); } } catch (ex) { - traceError('UniversalRemoteKernelFinder: Failed to write to cache', ex); + logger.error('UniversalRemoteKernelFinder: Failed to write to cache', ex); } } diff --git a/src/kernels/jupyter/finder/remoteKernelFinderController.ts b/src/kernels/jupyter/finder/remoteKernelFinderController.ts index b79512c004a..e0c6a237f13 100644 --- a/src/kernels/jupyter/finder/remoteKernelFinderController.ts +++ b/src/kernels/jupyter/finder/remoteKernelFinderController.ts @@ -24,7 +24,7 @@ import { generateIdFromRemoteProvider } from '../jupyterUtils'; import { swallowExceptions } from '../../../platform/common/utils/decorators'; import { JupyterServerCollection, JupyterServerProvider } from '../../../api'; import { CancellationTokenSource } from 'vscode'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IRemoteKernelFinderController } from './types'; import { CodespaceExtensionId } from '../../../platform/common/constants'; import { trackRemoteServerDisplayName } from '../connection/jupyterServerProviderRegistry'; @@ -161,7 +161,7 @@ export class RemoteKernelFinderController implements IRemoteKernelFinderControll } }); } catch (ex) { - traceError(`Failed to get servers for Collection ${collection.id} in ${collection.extensionId}`, ex); + logger.error(`Failed to get servers for Collection ${collection.id} in ${collection.extensionId}`, ex); } finally { token.dispose(); } diff --git a/src/kernels/jupyter/interpreter/jupyterCommand.node.ts b/src/kernels/jupyter/interpreter/jupyterCommand.node.ts index 837dfb5114c..385c96b4c28 100644 --- a/src/kernels/jupyter/interpreter/jupyterCommand.node.ts +++ b/src/kernels/jupyter/interpreter/jupyterCommand.node.ts @@ -4,7 +4,7 @@ import { SpawnOptions } from 'child_process'; import { inject, injectable } from 'inversify'; import * as path from '../../../platform/vscode-path/path'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { ExecutionResult } from '../../../platform/common/process/types.node'; import { EXTENSION_ROOT_DIR } from '../../../platform/constants.node'; import { PythonEnvironment } from '../../../platform/pythonEnvironments/info'; @@ -122,7 +122,7 @@ export class InterpreterJupyterKernelSpecCommand extends InterpreterJupyterComma const defaultAction = () => { if (exception) { - traceError(`Exception attempting to enumerate kernelspecs: `, exception); + logger.error(`Exception attempting to enumerate kernelspecs: `, exception); throw exception; } return output; @@ -150,7 +150,7 @@ export class InterpreterJupyterKernelSpecCommand extends InterpreterJupyterComma return output; } } catch (innerEx) { - traceError('Failed to get a list of the kernelspec using python script', innerEx); + logger.error('Failed to get a list of the kernelspec using python script', innerEx); } return defaultAction(); } diff --git a/src/kernels/jupyter/interpreter/jupyterInterpreterDependencyService.node.ts b/src/kernels/jupyter/interpreter/jupyterInterpreterDependencyService.node.ts index d8da3f14941..d1dccd6f9fe 100644 --- a/src/kernels/jupyter/interpreter/jupyterInterpreterDependencyService.node.ts +++ b/src/kernels/jupyter/interpreter/jupyterInterpreterDependencyService.node.ts @@ -4,7 +4,7 @@ import { inject, injectable } from 'inversify'; import { CancellationToken, CancellationTokenSource, Uri, env, window } from 'vscode'; import { raceCancellation } from '../../../platform/common/cancellation'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { DataScience, Common } from '../../../platform/common/utils/localize'; import { noop } from '../../../platform/common/utils/misc'; import { EnvironmentType, PythonEnvironment } from '../../../platform/pythonEnvironments/info'; @@ -299,7 +299,7 @@ export class JupyterInterpreterDependencyService { .exec(['--version'], { throwOnStdErr: true }) .then(() => true) .catch((e) => { - traceError(`Kernel spec not found: `, e); + logger.error(`Kernel spec not found: `, e); return false; }); } diff --git a/src/kernels/jupyter/interpreter/jupyterInterpreterSelector.node.ts b/src/kernels/jupyter/interpreter/jupyterInterpreterSelector.node.ts index c2e43a80502..96d2348fbb1 100644 --- a/src/kernels/jupyter/interpreter/jupyterInterpreterSelector.node.ts +++ b/src/kernels/jupyter/interpreter/jupyterInterpreterSelector.node.ts @@ -7,7 +7,7 @@ import { IServiceContainer } from '../../../platform/ioc/types'; import { CancellationTokenSource, workspace } from 'vscode'; import { IInterpreterService } from '../../../platform/interpreter/contracts'; import { InputFlowAction } from '../../../platform/common/utils/multiStepInput'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { getPythonEnvironmentCategory, pythonEnvironmentQuickPick @@ -101,7 +101,7 @@ export class JupyterInterpreterSelector { } return item; } catch (ex) { - traceError(`Failed to select a Python Environment to start Jupyter`, ex); + logger.error(`Failed to select a Python Environment to start Jupyter`, ex); } finally { dispose(disposables); } diff --git a/src/kernels/jupyter/interpreter/jupyterInterpreterSubCommandExecutionService.node.ts b/src/kernels/jupyter/interpreter/jupyterInterpreterSubCommandExecutionService.node.ts index 76139f75ba4..274852a7a73 100644 --- a/src/kernels/jupyter/interpreter/jupyterInterpreterSubCommandExecutionService.node.ts +++ b/src/kernels/jupyter/interpreter/jupyterInterpreterSubCommandExecutionService.node.ts @@ -5,7 +5,7 @@ import { inject, injectable, named } from 'inversify'; import * as path from '../../../platform/vscode-path/path'; import * as uriPath from '../../../platform/vscode-path/resources'; import { CancellationToken } from 'vscode'; -import { traceError, traceVerbose, traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { SpawnOptions, ObservableExecutionResult } from '../../../platform/common/process/types.node'; import { IOutputChannel } from '../../../platform/common/types'; import { DataScience } from '../../../platform/common/utils/localize'; @@ -123,16 +123,16 @@ export class JupyterInterpreterSubCommandExecutionService ...envVars, JUPYTER_PATH: jupyterDataPaths.join(path.delimiter) }; - traceVerbose(`Start Jupyter Notebook with JUPYTER_PATH=${jupyterDataPaths.join(path.delimiter)}`); - traceVerbose(`Start Jupyter Notebook with PYTHONPATH=${envVars['PYTHONPATH'] || ''}`); + logger.debug(`Start Jupyter Notebook with JUPYTER_PATH=${jupyterDataPaths.join(path.delimiter)}`); + logger.debug(`Start Jupyter Notebook with PYTHONPATH=${envVars['PYTHONPATH'] || ''}`); const pathVariables = Object.keys(envVars).filter((key) => key.toLowerCase() === 'path'); if (pathVariables.length) { const pathValues = pathVariables .map((pathVariable) => `${pathVariable}=${envVars[pathVariable]}`) .join(','); - traceVerbose(`Start Jupyter Notebook with PATH variable. ${pathValues}`); + logger.debug(`Start Jupyter Notebook with PATH variable. ${pathValues}`); } else { - traceError(`Start Jupyter Notebook without a PATH variable`); + logger.error(`Start Jupyter Notebook without a PATH variable`); } return executionService.execModuleObservable('jupyter', ['notebook'].concat(notebookArgs), spawnOptions); } @@ -153,7 +153,7 @@ export class JupyterInterpreterSubCommandExecutionService // Parse out our results, return undefined if we can't suss it out serverInfos = JSON.parse(serverInfoString.stdout.trim()) as JupyterServerInfo[]; } catch (err) { - traceWarning('Failed to parse JSON when getting server info out from getServerInfo.py', err); + logger.warn('Failed to parse JSON when getting server info out from getServerInfo.py', err); return; } return serverInfos; diff --git a/src/kernels/jupyter/interpreter/nbconvertExportToPythonService.node.ts b/src/kernels/jupyter/interpreter/nbconvertExportToPythonService.node.ts index a370f784df0..9ba8df3abc7 100644 --- a/src/kernels/jupyter/interpreter/nbconvertExportToPythonService.node.ts +++ b/src/kernels/jupyter/interpreter/nbconvertExportToPythonService.node.ts @@ -4,7 +4,7 @@ import { inject, injectable } from 'inversify'; import { CancellationToken, Uri } from 'vscode'; import { IPythonExecutionFactory } from '../../../platform/interpreter/types.node'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { reportAction } from '../../../platform/progress/decorator'; import { ReportableAction } from '../../../platform/progress/types'; import { PythonEnvironment } from '../../../platform/pythonEnvironments/info'; @@ -40,7 +40,7 @@ export class NbConvertExportToPythonService { // We can't check stderr (as nbconvert puts diag output there) but we need to verify here that we actually // converted something. If it's zero size then just raise an error if (output.stdout === '') { - traceError('nbconvert zero size output'); + logger.error('nbconvert zero size output'); throw new Error(output.stderr); } else { return output.stdout; diff --git a/src/kernels/jupyter/jupyterUtils.ts b/src/kernels/jupyter/jupyterUtils.ts index 60748f78b6b..e41b53e7015 100644 --- a/src/kernels/jupyter/jupyterUtils.ts +++ b/src/kernels/jupyter/jupyterUtils.ts @@ -13,7 +13,7 @@ import { sendTelemetryEvent } from '../../telemetry'; import { Identifiers, JVSC_EXTENSION_ID, Telemetry, isBuiltInJupyterProvider } from '../../platform/common/constants'; import { computeHash } from '../../platform/common/crypto'; import { IJupyterServerUri } from '../../api'; -import { traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IJupyterRequestAgentCreator, IJupyterRequestCreator, JupyterServerProviderHandle } from './types'; export function expandWorkingDir( @@ -244,5 +244,5 @@ export function getOwnerExtensionOfProviderHandle(id: string) { if (id === 'github-codespaces') { return 'GitHub.codespaces'; } - traceWarning(`Extension Id not found for server Id ${id}`); + logger.warn(`Extension Id not found for server Id ${id}`); } diff --git a/src/kernels/jupyter/launcher/jupyterConnectionWaiter.node.ts b/src/kernels/jupyter/launcher/jupyterConnectionWaiter.node.ts index 3cbde26af75..441e93f80a4 100644 --- a/src/kernels/jupyter/launcher/jupyterConnectionWaiter.node.ts +++ b/src/kernels/jupyter/launcher/jupyterConnectionWaiter.node.ts @@ -3,7 +3,7 @@ import { Disposable, Uri } from 'vscode'; import { IConfigurationService, IDisposable } from '../../../platform/common/types'; -import { traceError, traceWarning, traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { ObservableExecutionResult, Output } from '../../../platform/common/process/types.node'; import { createDeferred } from '../../../platform/common/utils/async'; import { DataScience } from '../../../platform/common/utils/localize'; @@ -59,13 +59,13 @@ export class JupyterConnectionWaiter implements IDisposable { // Listen on stderr for its connection information this.subscriptions.push( launchResult.out.onDidChange((output: Output) => { - traceVerbose(output.out); + logger.debug(output.out); this.output += output.out; if (RegExpValues.HttpPattern.exec(this.output) && !this.startPromise.completed) { // .then so that we can keep from pushing aync up to the subscribed observable function this.getServerInfo() .then((serverInfos) => this.getJupyterURL(serverInfos, this.output)) - .catch((ex) => traceWarning('Failed to get server info', ex)); + .catch((ex) => logger.warn('Failed to get server info', ex)); } // Sometimes jupyter will return a 403 error. Not sure why. We used @@ -109,7 +109,7 @@ export class JupyterConnectionWaiter implements IDisposable { try { url = new URL(uriString); } catch (err) { - traceError(`Failed to parse ${uriString}`, err); + logger.error(`Failed to parse ${uriString}`, err); // Failed to parse the url either via server infos or the string this.rejectStartPromise(DataScience.jupyterLaunchNoURL); return; diff --git a/src/kernels/jupyter/launcher/jupyterServerHelper.node.ts b/src/kernels/jupyter/launcher/jupyterServerHelper.node.ts index 16232a749dd..279ca1f86ad 100644 --- a/src/kernels/jupyter/launcher/jupyterServerHelper.node.ts +++ b/src/kernels/jupyter/launcher/jupyterServerHelper.node.ts @@ -4,7 +4,7 @@ import uuid from 'uuid/v4'; import { CancellationToken, Uri, workspace } from 'vscode'; import { inject, injectable, optional } from 'inversify'; -import { traceError, traceInfo, traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IDisposableRegistry, IAsyncDisposableRegistry, @@ -77,7 +77,7 @@ export class JupyterServerHelper implements IJupyterServerHelper { if (!this.cache) { const promise = (this.cache = this.startJupyterWithRetry(resource, cancelToken)); promise.catch((ex) => { - traceError(`Failed to start the Jupyter Server`, ex); + logger.error(`Failed to start the Jupyter Server`, ex); if (this.cache === promise) { this.cache = undefined; } @@ -126,14 +126,14 @@ export class JupyterServerHelper implements IJupyterServerHelper { // Start or connect to the process connection = await this.startImpl(resource, cancelToken); - traceVerbose(`Connection complete server`); + logger.debug(`Connection complete server`); return connection; } catch (err) { lastTryError = err; if (err instanceof JupyterWaitForIdleError && tryCount < maxTries) { // Special case. This sometimes happens where jupyter doesn't ever connect. Cleanup after // ourselves and propagate the failure outwards. - traceInfo('Retry because of wait for idle problem.'); + logger.info('Retry because of wait for idle problem.'); // Close existing connection. connection?.dispose(); @@ -158,7 +158,7 @@ export class JupyterServerHelper implements IJupyterServerHelper { private async startImpl(resource: Resource, cancelToken: CancellationToken): Promise { // If our uri is undefined or if it's set to local launch we need to launch a server locally // If that works, then attempt to start the server - traceVerbose(`Launching server`); + logger.debug(`Launching server`); const settings = this.configuration.getSettings(resource); const useDefaultConfig = settings.useDefaultConfigForJupyter; const workingDir = await computeWorkingDirectory(resource); diff --git a/src/kernels/jupyter/launcher/jupyterServerProvider.node.ts b/src/kernels/jupyter/launcher/jupyterServerProvider.node.ts index 72b72bd6ca1..d5c11dc2cd0 100644 --- a/src/kernels/jupyter/launcher/jupyterServerProvider.node.ts +++ b/src/kernels/jupyter/launcher/jupyterServerProvider.node.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { inject, injectable, optional } from 'inversify'; -import { traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { DataScience } from '../../../platform/common/utils/localize'; import { IInterpreterService } from '../../../platform/interpreter/contracts'; import { JupyterInstallError } from '../../../platform/errors/jupyterInstallError'; @@ -42,18 +42,18 @@ export class JupyterServerProvider implements IJupyterServerProvider { // Check to see if we support ipykernel or not try { - traceVerbose(`Checking for server usability.`); + logger.debug(`Checking for server usability.`); const usable = await this.checkUsable(); if (!usable) { - traceVerbose('Server not usable (should ask for install now)'); + logger.debug('Server not usable (should ask for install now)'); // Indicate failing. throw new JupyterInstallError( DataScience.jupyterNotSupported(await jupyterServerHelper.getJupyterServerError()) ); } // Then actually start the server - traceVerbose(`Starting notebook server.`); + logger.debug(`Starting notebook server.`); const result = await jupyterServerHelper.startServer(options.resource, options.token); Cancellation.throwIfCanceled(options.token); return result; diff --git a/src/kernels/jupyter/launcher/jupyterServerStarter.node.ts b/src/kernels/jupyter/launcher/jupyterServerStarter.node.ts index de0d5c69e45..46d00f47f62 100644 --- a/src/kernels/jupyter/launcher/jupyterServerStarter.node.ts +++ b/src/kernels/jupyter/launcher/jupyterServerStarter.node.ts @@ -10,7 +10,7 @@ import { CancellationToken, Uri } from 'vscode'; import { Cancellation, isCancellationError, raceCancellationError } from '../../../platform/common/cancellation'; import { JUPYTER_OUTPUT_CHANNEL } from '../../../platform/common/constants'; import { dispose } from '../../../platform/common/utils/lifecycle'; -import { traceInfo, traceError, traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IFileSystem, TemporaryDirectory } from '../../../platform/common/platform/types'; import { IDisposable, IOutputChannel, Resource } from '../../../platform/common/types'; import { DataScience } from '../../../platform/common/utils/localize'; @@ -65,7 +65,7 @@ export class JupyterServerStarter implements IJupyterServerStarter { workingDirectory: Uri, cancelToken: CancellationToken ): Promise { - traceInfo('Starting Jupyter Server'); + logger.info('Starting Jupyter Server'); // Now actually launch it let exitCode: number | null = 0; let starter: JupyterConnectionWaiter | undefined; @@ -115,7 +115,7 @@ export class JupyterServerStarter implements IJupyterServerStarter { } // Wait for the connection information on this result - traceVerbose('Waiting for Jupyter Notebook'); + logger.debug('Waiting for Jupyter Notebook'); starter = new JupyterConnectionWaiter( launchResult, Uri.file(tempDir.path), @@ -141,7 +141,7 @@ export class JupyterServerStarter implements IJupyterServerStarter { UsedPorts.add(port); } } catch (ex) { - traceError(`Parsing failed ${connection.baseUrl}`, ex); + logger.error(`Parsing failed ${connection.baseUrl}`, ex); } dispose(disposables); return connection; @@ -255,7 +255,7 @@ export class JupyterServerStarter implements IJupyterServerStarter { // as starting jupyter with all of the defaults. const configFile = path.join(tempDir.path, 'jupyter_notebook_config.py'); await this.fs.writeFile(Uri.file(configFile), ''); - traceVerbose(`Generating custom default config at ${configFile}`); + logger.debug(`Generating custom default config at ${configFile}`); // Create extra args based on if we have a config or not return `--config=${configFile}`; diff --git a/src/kernels/jupyter/launcher/serverPreload.node.ts b/src/kernels/jupyter/launcher/serverPreload.node.ts index 823aa6020e6..e5aca0709a5 100644 --- a/src/kernels/jupyter/launcher/serverPreload.node.ts +++ b/src/kernels/jupyter/launcher/serverPreload.node.ts @@ -5,7 +5,7 @@ import { inject, injectable, named } from 'inversify'; import { CancellationTokenSource, Memento, NotebookDocument, workspace } from 'vscode'; import { IExtensionSyncActivationService } from '../../../platform/activation/types'; import { PYTHON_LANGUAGE } from '../../../platform/common/constants'; -import { traceInfo, traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IConfigurationService, IDisposableRegistry, @@ -76,7 +76,7 @@ export class ServerPreload implements IExtensionSyncActivationService { const source = new CancellationTokenSource(); const ui = new DisplayOptions(true); try { - traceInfo(`Attempting to start a server because of preload conditions ...`); + logger.info(`Attempting to start a server because of preload conditions ...`); // If it didn't start, attempt for local and if allowed. if (!this.configService.getSettings(undefined).disableJupyterAutoStart) { @@ -88,7 +88,7 @@ export class ServerPreload implements IExtensionSyncActivationService { }); } } catch (exc) { - traceError(`Error starting server in serverPreload: `, exc); + logger.error(`Error starting server in serverPreload: `, exc); } finally { ui.dispose(); source.dispose(); diff --git a/src/kernels/jupyter/session/jupyterKernelService.node.ts b/src/kernels/jupyter/session/jupyterKernelService.node.ts index aa928b87386..57fead3efb2 100644 --- a/src/kernels/jupyter/session/jupyterKernelService.node.ts +++ b/src/kernels/jupyter/session/jupyterKernelService.node.ts @@ -6,7 +6,7 @@ import { inject, injectable } from 'inversify'; import * as path from '../../../platform/vscode-path/path'; import * as uriPath from '../../../platform/vscode-path/resources'; import { CancellationToken, Uri } from 'vscode'; -import { traceInfo, traceVerbose, traceDecoratorError, traceError, traceWarning } from '../../../platform/logging'; +import { logger, errorDecorator } from '../../../platform/logging'; import { getDisplayPath, getFilePath } from '../../../platform/common/platform/fs-paths'; import { IFileSystemNode } from '../../../platform/common/platform/types.node'; import { Resource, ReadWrite, IDisplayOptions } from '../../../platform/common/types'; @@ -57,7 +57,7 @@ export class JupyterKernelService implements IJupyterKernelService { cancelToken: CancellationToken, cannotChangeKernels?: boolean ): Promise { - traceVerbose(`Check if a kernel ${kernel.id} is usable`); + logger.debug(`Check if a kernel ${kernel.id} is usable`); // When dealing with Python kernels, and we have an interpreter, make sure it has the correct dependencies installed if (isKernelLaunchedViaLocalPythonIPyKernel(kernel) && kernel.interpreter) { const result = await this.kernelDependencyService.installMissingDependencies({ @@ -102,10 +102,10 @@ export class JupyterKernelService implements IJupyterKernelService { // Update the kernel environment to use the interpreter's latest if (kernel.interpreter && specFile) { - traceVerbose(`Updating Kernel Environment for ${kernel.id} for interpreter ${kernel.interpreter.id}`); + logger.debug(`Updating Kernel Environment for ${kernel.id} for interpreter ${kernel.interpreter.id}`); await this.updateKernelEnvironment(resource, kernel, specFile, cancelToken); } else { - traceVerbose(`Not Updating Kernel Environment for ${kernel.id}`); + logger.debug(`Not Updating Kernel Environment for ${kernel.id}`); } } } @@ -118,7 +118,7 @@ export class JupyterKernelService implements IJupyterKernelService { * - metadata.interpreter = Interpreter information (useful in finding a kernel that matches a given interpreter) * - env = Will have environment variables of the activated environment. */ - @traceDecoratorError('Failed to register an interpreter as a kernel') + @errorDecorator('Failed to register an interpreter as a kernel') private async registerKernel( kernel: LocalKernelConnectionMetadata, cancelToken: CancellationToken @@ -135,7 +135,7 @@ export class JupyterKernelService implements IJupyterKernelService { // If this file already exists, we can just exit if (await this.fs.exists(kernelSpecFilePath)) { - traceInfo(`Kernel spec file for ${kernel.id} already exists ${getDisplayPath(kernelSpecFilePath)}`); + logger.info(`Kernel spec file for ${kernel.id} already exists ${getDisplayPath(kernelSpecFilePath)}`); return kernelSpecFilePath.fsPath; } @@ -164,8 +164,8 @@ export class JupyterKernelService implements IJupyterKernelService { }; } - traceInfo(`RegisterKernel for ${kernel.id} into ${getDisplayPath(kernelSpecFilePath)}`); - traceVerbose( + logger.info(`RegisterKernel for ${kernel.id} into ${getDisplayPath(kernelSpecFilePath)}`); + logger.debug( `RegisterKernel for ${kernel.id} into ${getDisplayPath(kernelSpecFilePath)} with contents ${JSON.stringify( contents )}` @@ -213,7 +213,7 @@ export class JupyterKernelService implements IJupyterKernelService { // Make sure the file exists if (!(await this.fs.exists(Uri.file(kernelSpecFilePath)))) { - traceWarning( + logger.warn( `Spec file for ${kernelConnection.id} does not exist ${kernelSpecFilePath} hence not updating env vars.` ); return; @@ -231,7 +231,7 @@ export class JupyterKernelService implements IJupyterKernelService { if (specModel.metadata?.interpreter) { // Ensure we use a fully qualified path to the python interpreter in `argv`. if (isKernelLaunchedViaLocalPythonIPyKernel(kernel)) { - traceVerbose( + logger.debug( `Python KernelSpec argv[0] updated for ${kernelConnection.id} from '${ specModel.argv[0] }' to '${getDisplayPath(interpreter.uri)}'` @@ -246,7 +246,7 @@ export class JupyterKernelService implements IJupyterKernelService { // eslint-disable-next-line @typescript-eslint/no-explicit-any specModel.metadata.interpreter = interpreter as any; } else { - traceVerbose(`KernelSpec argv[0] not updated for ${kernelConnection.id} ('${specModel.argv[0]}')`); + logger.debug(`KernelSpec argv[0] not updated for ${kernelConnection.id} ('${specModel.argv[0]}')`); } specModel.env = await this.kernelEnvVars.getEnvironmentVariables(resource, interpreter, specedKernel); @@ -257,7 +257,7 @@ export class JupyterKernelService implements IJupyterKernelService { // Update the kernel.json with our new stuff. await this.fs.writeFile(uri, JSON.stringify(specModel, undefined, 2)); - traceVerbose( + logger.debug( `Updated kernel spec for ${kernelConnection.id} with environment variables for ${getDisplayPath( uri )}` @@ -273,7 +273,7 @@ export class JupyterKernelService implements IJupyterKernelService { if (cancelToken?.isCancellationRequested) { return; } - traceError( + logger.error( `Failed to update kernel spec for ${ kernelConnection.id } with environment variables for ${getDisplayPath(uri)}`, @@ -282,7 +282,7 @@ export class JupyterKernelService implements IJupyterKernelService { throw ex; } } else { - traceWarning(`Either Kernel spec file or root spec file path does not exist for ${kernelConnection.id}.`); + logger.warn(`Either Kernel spec file or root spec file path does not exist for ${kernelConnection.id}.`); } } } diff --git a/src/kernels/jupyter/session/jupyterKernelService.web.ts b/src/kernels/jupyter/session/jupyterKernelService.web.ts index 97121c31d27..5430b428c5f 100644 --- a/src/kernels/jupyter/session/jupyterKernelService.web.ts +++ b/src/kernels/jupyter/session/jupyterKernelService.web.ts @@ -3,7 +3,7 @@ import { injectable } from 'inversify'; import { CancellationToken } from 'vscode'; -import { traceVerbose, logValue, ignoreLogging } from '../../../platform/logging'; +import { logger, logValue, ignoreLogging } from '../../../platform/logging'; import { Resource, IDisplayOptions } from '../../../platform/common/types'; import { KernelConnectionMetadata } from '../../types'; import { IJupyterKernelService } from '../types'; @@ -29,7 +29,7 @@ export class JupyterKernelService implements IJupyterKernelService { @ignoreLogging() _cancelToken: CancellationToken, _cannotChangeKernels?: boolean ): Promise { - traceVerbose('Check if a kernel is usable'); + logger.debug('Check if a kernel is usable'); // For now web kernels are always usable. } } diff --git a/src/kernels/jupyter/session/jupyterKernelSessionFactory.ts b/src/kernels/jupyter/session/jupyterKernelSessionFactory.ts index e7917ee69c5..76d62d09dc4 100644 --- a/src/kernels/jupyter/session/jupyterKernelSessionFactory.ts +++ b/src/kernels/jupyter/session/jupyterKernelSessionFactory.ts @@ -17,7 +17,7 @@ import { isRemoteConnection } from '../../types'; import { IJupyterKernelService, IJupyterServerProvider } from '../types'; -import { traceError, traceInfo, traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { inject, injectable, optional } from 'inversify'; import { noop, swallowExceptions } from '../../../platform/common/utils/misc'; import { SessionDisposedError } from '../../../platform/errors/sessionDisposedError'; @@ -119,7 +119,7 @@ export class JupyterKernelSessionFactory implements IKernelSessionFactory { swallowExceptions(() => session.dispose()); } Cancellation.throwIfCanceled(options.token); - traceInfo(`Started session for kernel ${options.kernelConnection.kind}:${options.kernelConnection.id}`); + logger.info(`Started session for kernel ${options.kernelConnection.kind}:${options.kernelConnection.id}`); const wrapperSession = new JupyterSessionWrapper( session, @@ -182,7 +182,7 @@ export class JupyterKernelSessionFactory implements IKernelSessionFactory { try { await Promise.all([sessionManager.getRunningKernels(), sessionManager.getKernelSpecs()]); } catch (ex) { - traceError( + logger.error( 'Failed to fetch running kernels from remote server, connection may be outdated or remote server may be unreachable', ex ); @@ -262,7 +262,7 @@ export class JupyterKernelSessionFactory implements IKernelSessionFactory { ) ); } else { - traceVerbose(`createNewKernelSession ${options.kernelConnection?.id}`); + logger.debug(`createNewKernelSession ${options.kernelConnection?.id}`); session = await this.createNewSession(options); await waitForIdleOnSession( @@ -281,13 +281,13 @@ export class JupyterKernelSessionFactory implements IKernelSessionFactory { } catch (exc) { // Don't log errors if UI is disabled (e.g. auto starting a kernel) // Else we just pollute the logs with lots of noise. - const loggerFn = options.ui.disableUI ? traceVerbose : traceError; + const log = options.ui.disableUI ? logger.debug : logger.error; // Don't swallow known exceptions. if (exc instanceof BaseError) { - loggerFn('Failed to change kernel, re-throwing', exc); + log('Failed to change kernel, re-throwing', exc); throw exc; } else { - loggerFn('Failed to change kernel', exc); + log('Failed to change kernel', exc); // Throw a new exception indicating we cannot change. throw new JupyterInvalidKernelError(options.kernelConnection); } @@ -355,7 +355,7 @@ export class JupyterKernelSessionFactory implements IKernelSessionFactory { if (!session.kernel) { throw new JupyterSessionStartError(new Error(`No kernel created`)); } - traceInfo(DataScience.createdNewKernel(options.connection.baseUrl, session?.kernel?.id || '')); + logger.info(DataScience.createdNewKernel(options.connection.baseUrl, session?.kernel?.id || '')); return session; } catch (ex) { if (ex instanceof JupyterSessionStartError) { diff --git a/src/kernels/jupyter/session/jupyterLabHelper.ts b/src/kernels/jupyter/session/jupyterLabHelper.ts index 367ae010eef..a5b06a365a3 100644 --- a/src/kernels/jupyter/session/jupyterLabHelper.ts +++ b/src/kernels/jupyter/session/jupyterLabHelper.ts @@ -11,7 +11,7 @@ import type { } from '@jupyterlab/services'; import { JSONObject } from '@lumino/coreutils'; import { Disposable } from 'vscode'; -import { traceError, traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IDisposable } from '../../../platform/common/types'; import { SessionDisposedError } from '../../../platform/errors/sessionDisposedError'; import { createInterpreterKernelSpec } from '../../helpers'; @@ -60,14 +60,14 @@ export class JupyterLabHelper { return; } this.disposed = true; - traceVerbose(`Disposing Jupyter Lab Helper`); + logger.debug(`Disposing Jupyter Lab Helper`); try { if (this.contentsManager) { - traceVerbose('SessionManager - dispose contents manager'); + logger.debug('SessionManager - dispose contents manager'); this.contentsManager.dispose(); } if (this.sessionManager && !this.sessionManager.isDisposed) { - traceVerbose('ShutdownSessionAndConnection - dispose session manager'); + logger.debug('ShutdownSessionAndConnection - dispose session manager'); // Make sure it finishes startup. await raceTimeout(10_000, this.sessionManager.ready); @@ -81,9 +81,9 @@ export class JupyterLabHelper { this.kernelSpecManager?.dispose(); } } catch (e) { - traceError(`Exception on Jupyter Lab Helper shutdown: `, e); + logger.error(`Exception on Jupyter Lab Helper shutdown: `, e); } finally { - traceVerbose('Finished disposing Jupyter Lab Helper'); + logger.debug('Finished disposing Jupyter Lab Helper'); } } @@ -141,7 +141,7 @@ export class JupyterLabHelper { const stopWatch = new StopWatch(); const specsManager = this.kernelSpecManager; if (!specsManager) { - traceError( + logger.error( `No SessionManager to enumerate kernelspecs (no specs manager). Returning a default kernel. Specs ${JSON.stringify( this.kernelSpecManager?.specs?.kernelspecs || {} )}.` @@ -225,7 +225,7 @@ export class JupyterLabHelper { ); return specs; } else { - traceError( + logger.error( `Jupyter Lab Helper cannot enumerate kernelspecs. Returning a default kernel. Specs ${JSON.stringify( kernelspecs )}.` @@ -241,7 +241,7 @@ export class JupyterLabHelper { return [await createInterpreterKernelSpec()]; } } catch (e) { - traceError(`Jupyter Lab Helper:getKernelSpecs failure: `, e); + logger.error(`Jupyter Lab Helper:getKernelSpecs failure: `, e); // For some reason this is failing. Just return nothing return []; } diff --git a/src/kernels/jupyter/session/jupyterRequestCreator.node.ts b/src/kernels/jupyter/session/jupyterRequestCreator.node.ts index 7b2b9b745ff..7c568ed2063 100644 --- a/src/kernels/jupyter/session/jupyterRequestCreator.node.ts +++ b/src/kernels/jupyter/session/jupyterRequestCreator.node.ts @@ -5,7 +5,7 @@ import { IJupyterRequestCreator } from '../types'; import * as nodeFetch from 'node-fetch'; import { ClassType } from '../../../platform/ioc/types'; import WebSocketIsomorphic from 'isomorphic-ws'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { noop } from '../../../platform/common/utils/misc'; import { KernelSocketWrapper } from '../../common/kernelSocketWrapper'; import { injectable } from 'inversify'; @@ -95,7 +95,7 @@ export class JupyterRequestCreator implements IJupyterRequestCreator { } }); } else { - traceError('KernelId not extracted from Kernel WebSocket URL'); + logger.error('KernelId not extracted from Kernel WebSocket URL'); } // Ping the websocket connection every 30 seconds to make sure it stays alive @@ -128,7 +128,7 @@ export class JupyterRequestCreator implements IJupyterRequestCreator { } }); } else { - traceError('KernelId not extracted from Kernel WebSocket URL'); + logger.error('KernelId not extracted from Kernel WebSocket URL'); } // Ping the websocket connection every 30 seconds to make sure it stays alive diff --git a/src/kernels/jupyter/session/jupyterRequestCreator.web.ts b/src/kernels/jupyter/session/jupyterRequestCreator.web.ts index a1f2f6bd66e..f7e238a83c0 100644 --- a/src/kernels/jupyter/session/jupyterRequestCreator.web.ts +++ b/src/kernels/jupyter/session/jupyterRequestCreator.web.ts @@ -4,7 +4,7 @@ import { injectable } from 'inversify'; import WebSocketIsomorphic from 'isomorphic-ws'; import { ClassType } from '../../../platform/ioc/types'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { KernelSocketWrapper } from '../../common/kernelSocketWrapper'; import { IJupyterRequestCreator } from '../types'; import { KernelSocketMap } from '../../kernelSocket'; @@ -79,7 +79,7 @@ export class JupyterRequestCreator implements IJupyterRequestCreator { } }; } else { - traceError('KernelId not extracted from Kernel WebSocket URL'); + logger.error('KernelId not extracted from Kernel WebSocket URL'); } // TODO: Implement ping. Well actually see if ping is necessary @@ -149,7 +149,7 @@ export class JupyterRequestCreator implements IJupyterRequestCreator { } }; } else { - traceError('KernelId not extracted from Kernel WebSocket URL'); + logger.error('KernelId not extracted from Kernel WebSocket URL'); } // TODO: Implement ping. Well actually see if ping is necessary diff --git a/src/kernels/jupyter/session/jupyterSession.ts b/src/kernels/jupyter/session/jupyterSession.ts index 50ae5bb06e1..38078465788 100644 --- a/src/kernels/jupyter/session/jupyterSession.ts +++ b/src/kernels/jupyter/session/jupyterSession.ts @@ -3,7 +3,7 @@ import type { KernelMessage, Session } from '@jupyterlab/services'; import { CancellationError, CancellationToken, CancellationTokenSource, Uri } from 'vscode'; -import { traceVerbose, traceWarning, traceInfoIfCI } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { Resource, IDisposable } from '../../../platform/common/types'; import { raceTimeout } from '../../../platform/common/utils/async'; import { suppressShutdownErrors } from '../../common/baseJupyterSession'; @@ -35,7 +35,7 @@ export class JupyterSessionWrapper if (this.session?.kernel) { return this.session.kernel.status; } - traceInfoIfCI( + logger.ci( `Kernel status not started because real session is ${ this.session ? 'defined' : 'undefined' } & real kernel is ${this.session?.kernel ? 'defined' : 'undefined'}` @@ -69,7 +69,7 @@ export class JupyterSessionWrapper try { await waitForIdleOnSession(this.kernelConnectionMetadata, this.resource, this.session, timeout, token); } catch (ex) { - traceInfoIfCI(`Error waiting for idle`, ex); + logger.ci(`Error waiting for idle`, ex); await this.shutdown().catch(noop); throw ex; } @@ -128,13 +128,13 @@ export class JupyterSessionWrapper this._isDisposed = true; // We are only interested in our stack, not in VS Code or others. const stack = (new Error().stack || '').split('\n').filter((l) => l.includes(JVSC_EXTENSION_ID)); - traceVerbose(`Shutdown session - current session, called from \n ${stack.map((l) => ` ${l}`).join('\n')}`); + logger.debug(`Shutdown session - current session, called from \n ${stack.map((l) => ` ${l}`).join('\n')}`); const kernelIdForLogging = `${this.session.kernel?.id}, ${this.kernelConnectionMetadata.id}`; - traceVerbose(`shutdownSession ${kernelIdForLogging} - start`); + logger.debug(`shutdownSession ${kernelIdForLogging} - start`); try { if (shutdownEvenIfRemote || this.canShutdownSession()) { try { - traceVerbose(`Session can be shutdown ${this.kernelConnectionMetadata.id}`); + logger.debug(`Session can be shutdown ${this.kernelConnectionMetadata.id}`); suppressShutdownErrors(this.session.kernel); // Shutdown may fail if the process has been killed if (!this.session.isDisposed) { @@ -148,13 +148,13 @@ export class JupyterSessionWrapper this.session.dispose(); } } catch (e) { - traceWarning('Failures in disposing the session', e); + logger.warn('Failures in disposing the session', e); } } finally { this.didShutdown.fire(); } } else { - traceVerbose(`Session cannot be shutdown ${this.kernelConnectionMetadata.id}`); + logger.debug(`Session cannot be shutdown ${this.kernelConnectionMetadata.id}`); } try { // If session.shutdown didn't work, just dispose @@ -162,14 +162,14 @@ export class JupyterSessionWrapper this.session.dispose(); } } catch (e) { - traceWarning('Failures in disposing the session', e); + logger.warn('Failures in disposing the session', e); } super.dispose(); - traceVerbose('Shutdown session -- complete'); + logger.debug('Shutdown session -- complete'); } catch (e) { - traceWarning('Failures in disposing the session', e); + logger.warn('Failures in disposing the session', e); } - traceVerbose(`shutdownSession ${kernelIdForLogging} - shutdown complete`); + logger.debug(`shutdownSession ${kernelIdForLogging} - shutdown complete`); } private canShutdownSession(): boolean { if (isLocalConnection(this.kernelConnectionMetadata)) { diff --git a/src/kernels/kernel.ts b/src/kernels/kernel.ts index ab010075dd4..44eec547cf2 100644 --- a/src/kernels/kernel.ts +++ b/src/kernels/kernel.ts @@ -25,7 +25,7 @@ import { } from '../platform/common/constants'; import { WrappedError } from '../platform/errors/types'; import { splitLines } from '../platform/common/helpers'; -import { traceInfo, traceInfoIfCI, traceError, traceVerbose, traceWarning, traceTrace } from '../platform/logging'; +import { logger } from '../platform/logging'; import { getDisplayPath, getFilePath } from '../platform/common/platform/fs-paths'; import { Resource, IDisposable, IDisplayOptions } from '../platform/common/types'; import { createDeferred, raceTimeout, raceTimeoutError } from '../platform/common/utils/async'; @@ -256,16 +256,16 @@ abstract class BaseKernel implements IBaseKernel { const pendingExecutions = Promise.all( Array.from(this.hooks.get('willInterrupt') || new Set()).map((h) => h()) ); - traceInfo(`Interrupt requested ${getDisplayPath(this.resourceUri || this.uri)}`); + logger.info(`Interrupt requested ${getDisplayPath(this.resourceUri || this.uri)}`); let result: InterruptResult; try { const session = this._jupyterSessionPromise ? await this._jupyterSessionPromise.catch(() => undefined) : undefined; - traceInfo('Interrupt kernel execution'); + logger.info('Interrupt kernel execution'); if (!session) { - traceInfo('No kernel session to interrupt'); + logger.info('No kernel session to interrupt'); this._interruptPromise = undefined; result = InterruptResult.Success; } else { @@ -283,7 +283,7 @@ abstract class BaseKernel implements IBaseKernel { ).catch(noop); } - traceInfo(`Interrupt requested & sent for ${getDisplayPath(this.uri)} in notebookEditor.`); + logger.info(`Interrupt requested & sent for ${getDisplayPath(this.uri)} in notebookEditor.`); if (result === InterruptResult.TimedOut) { const message = DataScience.restartKernelAfterInterruptMessage( getDisplayNameOrNameOfKernelConnection(this.kernelConnectionMetadata) @@ -296,7 +296,9 @@ abstract class BaseKernel implements IBaseKernel { } } public async dispose(): Promise { - traceInfo(`Dispose Kernel '${getDisplayPath(this.uri)}' associated with '${getDisplayPath(this.resourceUri)}'`); + logger.info( + `Dispose Kernel '${getDisplayPath(this.uri)}' associated with '${getDisplayPath(this.resourceUri)}'` + ); this._disposing = true; if (this.disposingPromise) { return this.disposingPromise; @@ -336,7 +338,7 @@ abstract class BaseKernel implements IBaseKernel { public async restart(): Promise { try { const resourceType = getResourceType(this.resourceUri); - traceInfo(`Restart requested ${getDisplayPath(this.uri)}`); + logger.info(`Restart requested ${getDisplayPath(this.uri)}`); await Promise.all( Array.from(this.hooks.get('willRestart') || new Set()).map((h) => h(this._jupyterSessionPromise)) ); @@ -379,7 +381,7 @@ abstract class BaseKernel implements IBaseKernel { { resourceType } ); } catch (ex) { - traceError(`Restart failed ${getDisplayPath(this.uri)}`, ex); + logger.error(`Restart failed ${getDisplayPath(this.uri)}`, ex); this._ignoreJupyterSessionDisposedErrors = true; // If restart fails, kill the associated session. const session = this._session; @@ -405,7 +407,7 @@ abstract class BaseKernel implements IBaseKernel { // Indicate a restart occurred if it succeeds this._onRestarted.fire(); } catch (ex) { - traceError(`Failed to restart kernel ${getDisplayPath(this.uri)}`, ex); + logger.error(`Failed to restart kernel ${getDisplayPath(this.uri)}`, ex); throw ex; } finally { Promise.all(Array.from(this.hooks.get('restartCompleted') || new Set()).map((h) => h())).catch(noop); @@ -472,7 +474,7 @@ abstract class BaseKernel implements IBaseKernel { return session; }) .catch((ex) => { - traceInfoIfCI( + logger.ci( `Failed to create Jupyter Session in Kernel.startNotebook for ${getDisplayPath(this.uri)}` ); // If we fail also clear the promise. @@ -495,7 +497,7 @@ abstract class BaseKernel implements IBaseKernel { const restartHandler = (e: KernelMessage.Status) => { if (e === 'restarting' || e === 'autorestarting') { // We restarted the kernel. - traceWarning('Kernel restarting during interrupt'); + logger.warn('Kernel restarting during interrupt'); // Indicate we restarted the race below restarted.resolve(true); @@ -508,7 +510,7 @@ abstract class BaseKernel implements IBaseKernel { ); if (session && session.kernel) { - traceInfo(`Interrupting kernel: ${session.kernel.name}`); + logger.info(`Interrupting kernel: ${session.kernel.name}`); // Start our interrupt. If it fails, indicate a restart await raceTimeoutError( @@ -516,7 +518,7 @@ abstract class BaseKernel implements IBaseKernel { new KernelInterruptTimeoutError(this.kernelConnectionMetadata), session.kernel.interrupt() ).catch((exc) => { - traceWarning(`Error during interrupt: ${exc}`); + logger.warn(`Error during interrupt: ${exc}`); restarted.resolve(true); }); } @@ -599,7 +601,7 @@ abstract class BaseKernel implements IBaseKernel { } pythonInfo = ` (${info.filter((s) => s).join(', ')})`; } - traceInfo( + logger.info( `Starting Kernel ${this.kernelConnectionMetadata.kind}, ${ this.kernelConnectionMetadata.id } ${pythonInfo} for '${getDisplayPath(this.uri)}' (disableUI=${this.startupUI.disableUI})` @@ -630,12 +632,12 @@ abstract class BaseKernel implements IBaseKernel { // Don't log errors if UI is disabled (e.g. auto starting a kernel) // Else we just pollute the logs with lots of noise. if (this.startupUI.disableUI) { - traceVerbose( + logger.debug( `failed to create IJupyterKernelConnectionSession in kernel, UI Disabled = ${this.startupUI.disableUI}`, ex ); } else if (!this.startCancellation.token && !isCancellationError(ex)) { - traceError( + logger.error( `failed to create IJupyterKernelConnectionSession in kernel, UI Disabled = ${this.startupUI.disableUI}`, ex ); @@ -717,23 +719,23 @@ abstract class BaseKernel implements IBaseKernel { h(session, this.startCancellation.token).catch(noop) ) ); - traceVerbose(`Started running kernel initialization for ${getDisplayPath(this.uri)}`); + logger.debug(`Started running kernel initialization for ${getDisplayPath(this.uri)}`); if (!session) { - traceVerbose('Not running kernel initialization'); + logger.debug('Not running kernel initialization'); return; } if (!this.hookedSessionForEvents.has(session)) { this.hookedSessionForEvents.add(session); session.onDidKernelSocketChange((e) => this._onDidKernelSocketChange.fire(e)); session.onDidDispose(() => { - traceInfoIfCI( + logger.ci( `Kernel got disposed as a result of session.onDisposed (1) ${getDisplayPath( this.resourceUri || this.uri )}` ); // Ignore when session is disposed as a result of failed restarts. if (!this._ignoreJupyterSessionDisposedErrors) { - traceInfo( + logger.info( `Kernel got disposed as a result of session.onDisposed ${getDisplayPath( this.resourceUri || this.uri )} & _ignoreJupyterSessionDisposedErrors = false.` @@ -767,7 +769,7 @@ abstract class BaseKernel implements IBaseKernel { // This must happen early on as the state of the kernel needs to be synced with the Kernel in the webview (renderer) // And the longer we wait, the more data we need to hold onto in memory that later needs to be sent to the kernel in renderer. this.determineVersionOfIPyWidgets(session).catch((ex) => - traceError(`Failed to determine IPyWidget version`, ex) + logger.error(`Failed to determine IPyWidget version`, ex) ); // Gather all of the startup code at one time and execute as one cell @@ -778,7 +780,7 @@ abstract class BaseKernel implements IBaseKernel { traceErrorsMessage: 'Error executing jupyter extension internal startup code' }) ) - .catch((ex) => traceError(`Failed to execute internal startup code`, ex)); + .catch((ex) => logger.error(`Failed to execute internal startup code`, ex)); } else { // As users can have IPyWidgets at any point in time, we need to determine the version of ipywidgets // This must happen early on as the state of the kernel needs to be synced with the Kernel in the webview (renderer) @@ -799,17 +801,17 @@ abstract class BaseKernel implements IBaseKernel { // Then request our kernel info (indicates kernel is ready to go) const kernelInfo = tracker?.kernelInfo(); try { - traceVerbose('Requesting Kernel info'); + logger.debug('Requesting Kernel info'); this._info = await getKernelInfo(session, this.kernelConnectionMetadata, this.workspaceMemento); } catch (ex) { - traceWarning('Failed to request KernelInfo', ex); + logger.warn('Failed to request KernelInfo', ex); } kernelInfo?.stop(); const kernelIdle = tracker?.kernelIdle(); if (this.kernelConnectionMetadata.kind !== 'connectToLiveRemoteKernel') { - traceVerbose('End running kernel initialization, now waiting for idle'); + logger.debug('End running kernel initialization, now waiting for idle'); await session.waitForIdle(this.kernelSettings.launchTimeout, this.startCancellation.token); - traceVerbose('End running kernel initialization, session is idle'); + logger.debug('End running kernel initialization, session is idle'); } kernelIdle?.stop(); } finally { @@ -841,7 +843,7 @@ abstract class BaseKernel implements IBaseKernel { `; const version = await this.executeSilently(session, [codeToDetermineIPyWidgetsVersion]).catch((ex) => - traceError('Failed to determine version of IPyWidgets', ex) + logger.error('Failed to determine version of IPyWidgets', ex) ); if (Array.isArray(version)) { const isVersion8 = version.some( @@ -852,12 +854,12 @@ abstract class BaseKernel implements IBaseKernel { ); const newVersion = (this._ipywidgetsVersion = isVersion7 ? 7 : isVersion8 ? 8 : undefined); - traceTrace(`Determined IPyWidgets Version as ${newVersion}`); + logger.trace(`Determined IPyWidgets Version as ${newVersion}`); // If user does not have ipywidgets installed, then this event will never get fired. this._ipywidgetsVersion == newVersion; this._onIPyWidgetVersionResolved.fire(newVersion); } else { - traceWarning('Failed to determine IPyKernel Version', JSON.stringify(version)); + logger.warn('Failed to determine IPyKernel Version', JSON.stringify(version)); } }; await determineVersionImpl(); @@ -937,11 +939,11 @@ abstract class BaseKernel implements IBaseKernel { if (this.kernelSettings.themeMatplotlibPlots) { // We're theming matplotlibs, so we have to setup our default state. - traceInfoIfCI(`Initialize config for plots for ${getDisplayPath(this.resourceUri || this.uri)}`); + logger.ci(`Initialize config for plots for ${getDisplayPath(this.resourceUri || this.uri)}`); const matplotInit = CodeSnippets.MatplotLibInit; - traceVerbose(`Initialize matplotlib for ${getDisplayPath(this.resourceUri || this.uri)}`); + logger.debug(`Initialize matplotlib for ${getDisplayPath(this.resourceUri || this.uri)}`); // Force matplotlib to inline and save the default style. We'll use this later if we // get a request to update style results.push(...splitLines(matplotInit, { trim: false })); @@ -985,7 +987,7 @@ abstract class BaseKernel implements IBaseKernel { return; } if (!session.kernel) { - traceVerbose(`Not executing startup as there is no session, code: ${code}`); + logger.debug(`Not executing startup as there is no session, code: ${code}`); return; } return executeSilently(session.kernel, code.join('\n'), errorOptions); diff --git a/src/kernels/kernelDependencyService.node.ts b/src/kernels/kernelDependencyService.node.ts index b90dd9ca7b2..d77f2bd5a5a 100644 --- a/src/kernels/kernelDependencyService.node.ts +++ b/src/kernels/kernelDependencyService.node.ts @@ -4,7 +4,7 @@ import { inject, injectable, named } from 'inversify'; import { CancellationToken, CancellationTokenSource, Memento, Uri, env, window } from 'vscode'; import { raceCancellation } from '../platform/common/cancellation'; -import { traceInfo, traceError, traceInfoIfCI, traceDecoratorVerbose, logValue } from '../platform/logging'; +import { logger, debugDecorator, logValue } from '../platform/logging'; import { getDisplayPath } from '../platform/common/platform/fs-paths'; import { IMemento, GLOBAL_MEMENTO, Resource, IDisplayOptions } from '../platform/common/types'; import { DataScience, Common } from '../platform/common/utils/localize'; @@ -52,7 +52,7 @@ export class KernelDependencyService implements IKernelDependencyService { * Configures the python interpreter to ensure it can run a Jupyter Kernel by installing any missing dependencies. * If user opts not to install they can opt to select another interpreter. */ - @traceDecoratorVerbose('Install Missing Dependencies') + @debugDecorator('Install Missing Dependencies') public async installMissingDependencies({ resource, kernelConnection, @@ -78,7 +78,7 @@ export class KernelDependencyService implements IKernelDependencyService { return KernelInterpreterDependencyResponse.ok; } - traceInfo( + logger.info( `Check & install missing Kernel dependencies for ${getDisplayPath( kernelConnection.interpreter?.uri )}, ui.disabled=${ui.disableUI} for resource '${getDisplayPath(resource)}'` @@ -158,7 +158,7 @@ export class KernelDependencyService implements IKernelDependencyService { dependencyResponse = KernelInterpreterDependencyResponse.cancel; } } catch (ex) { - traceInfoIfCI(`Failed to install kernel dependency`, ex); + logger.ci(`Failed to install kernel dependency`, ex); // Failure occurred dependencyResponse = KernelInterpreterDependencyResponse.failed; } finally { @@ -167,7 +167,7 @@ export class KernelDependencyService implements IKernelDependencyService { } return dependencyResponse; } - @traceDecoratorVerbose('Are Dependencies Installed') + @debugDecorator('Are Dependencies Installed') public async areDependenciesInstalled( @logValue('id') kernelConnection: KernelConnectionMetadata, token?: CancellationToken, @@ -190,7 +190,7 @@ export class KernelDependencyService implements IKernelDependencyService { this.rawSupport.isSupported && (await isModulePresentInEnvironmentCache(this.memento, Product.ipykernel, kernelConnection.interpreter)) ) { - traceInfo( + logger.info( `IPyKernel found previously in this environment ${getDisplayPath(kernelConnection.interpreter.uri)}` ); return true; @@ -218,7 +218,7 @@ export class KernelDependencyService implements IKernelDependencyService { cannotChangeKernels?: boolean, installWithoutPrompting?: boolean ): Promise { - traceInfoIfCI( + logger.ci( `Run Installer for ${getDisplayPath(resource)} ui.disableUI=${ ui.disableUI }, cancelTokenSource.token.isCancellationRequested=${cancelTokenSource.token.isCancellationRequested}` @@ -371,7 +371,7 @@ export class KernelDependencyService implements IKernelDependencyService { }); return KernelInterpreterDependencyResponse.cancel; } catch (ex) { - traceError(`Failed to install ${productNameForTelemetry}`, ex); + logger.error(`Failed to install ${productNameForTelemetry}`, ex); sendKernelTelemetryEvent(resource, Telemetry.PythonModuleInstall, undefined, { action: 'error', moduleName: productNameForTelemetry, diff --git a/src/kernels/kernelExecution.ts b/src/kernels/kernelExecution.ts index bf5fdb71bad..bdbe06ff529 100644 --- a/src/kernels/kernelExecution.ts +++ b/src/kernels/kernelExecution.ts @@ -13,7 +13,7 @@ import { } from 'vscode'; import { getDisplayPath } from '../platform/common/platform/fs-paths'; import { IDisposable, IExtensionContext } from '../platform/common/types'; -import { traceInfo, traceVerbose } from '../platform/logging'; +import { logger } from '../platform/logging'; import { Telemetry } from '../telemetry'; import { DisplayOptions } from './displayOptions'; import { CellExecutionFactory } from './execution/cellExecution'; @@ -157,7 +157,7 @@ export class NotebookKernelExecution implements INotebookKernelExecution { cell, `NotebookKernelExecution.resumeCellExecution (completed), ${getDisplayPath(cell.notebook.uri)}` ); - traceVerbose(`Cell ${cell.index} executed ${success ? 'successfully' : 'with an error'}`); + logger.debug(`Cell ${cell.index} executed ${success ? 'successfully' : 'with an error'}`); } public async executeCell(cell: NotebookCell, codeOverride?: string | undefined): Promise { traceCellMessage(cell, `NotebookKernelExecution.executeCell (1), ${getDisplayPath(cell.notebook.uri)}`); @@ -190,7 +190,7 @@ export class NotebookKernelExecution implements INotebookKernelExecution { cell, `NotebookKernelExecution.executeCell completed (3), ${getDisplayPath(cell.notebook.uri)}` ); - traceVerbose(`Cell ${cell.index} executed ${success ? 'successfully' : 'with an error'}`); + logger.debug(`Cell ${cell.index} executed ${success ? 'successfully' : 'with an error'}`); sendKernelTelemetryEvent(this.kernel.resourceUri, Telemetry.ExecuteCell, { duration: stopWatch.elapsedTime }); @@ -227,7 +227,7 @@ export class NotebookKernelExecution implements INotebookKernelExecution { result = executionQueue.queueCode(code, extensionId, token); } if (extensionId !== JVSC_EXTENSION_ID) { - traceVerbose( + logger.debug( `Queue code ${result.executionId} from ${extensionId} after ${stopWatch.elapsedTime}ms:\n${code}` ); } @@ -237,7 +237,7 @@ export class NotebookKernelExecution implements INotebookKernelExecution { .finally(() => { completed = true; !token.isCancellationRequested && - traceVerbose(`Execution of code ${result.executionId} completed in ${stopWatch.elapsedTime}ms`); + logger.debug(`Execution of code ${result.executionId} completed in ${stopWatch.elapsedTime}ms`); if (extensionId !== JVSC_EXTENSION_ID) { sendKernelTelemetryEvent( this.kernel.resourceUri, @@ -268,7 +268,7 @@ export class NotebookKernelExecution implements INotebookKernelExecution { if (completed) { return; } - traceVerbose(`Code execution cancelled by extension ${extensionId}`); + logger.debug(`Code execution cancelled by extension ${extensionId}`); }, this, disposables @@ -302,7 +302,7 @@ export class NotebookKernelExecution implements INotebookKernelExecution { if (!executionQueue && this.kernel.kernelConnectionMetadata.kind !== 'connectToLiveRemoteKernel') { return; } - traceInfo('Interrupt kernel execution'); + logger.info('Interrupt kernel execution'); // First cancel all the cells & then wait for them to complete. // Both must happen together, we cannot just wait for cells to complete, as its possible // that cell1 has started & cell2 has been queued. If Cell1 completes, then Cell2 will start. @@ -335,7 +335,7 @@ export class NotebookKernelExecution implements INotebookKernelExecution { : Promise.resolve(); if (!session) { - traceInfo('No kernel session to interrupt'); + logger.info('No kernel session to interrupt'); await pendingCells; } } @@ -358,7 +358,7 @@ export class NotebookKernelExecution implements INotebookKernelExecution { workspace.onDidCloseNotebookDocument( async (e: NotebookDocument) => { if (e === document) { - traceVerbose(`Cancel executions after closing notebook ${getDisplayPath(e.uri)}`); + logger.debug(`Cancel executions after closing notebook ${getDisplayPath(e.uri)}`); if (!newCellExecutionQueue.failed || !newCellExecutionQueue.isEmpty) { await newCellExecutionQueue.cancel(true); } diff --git a/src/kernels/kernelInfo.ts b/src/kernels/kernelInfo.ts index 5ee322b92b4..00935a43225 100644 --- a/src/kernels/kernelInfo.ts +++ b/src/kernels/kernelInfo.ts @@ -4,7 +4,7 @@ import type { KernelMessage } from '@jupyterlab/services'; import { IKernelSession, KernelConnectionMetadata, isRemoteConnection } from './types'; import { Memento } from 'vscode'; -import { traceVerbose, traceWarning } from '../platform/logging'; +import { logger } from '../platform/logging'; import { noop } from '../platform/common/utils/misc'; import { sleep } from '../platform/common/utils/async'; @@ -67,9 +67,9 @@ export async function getKernelInfo( } const content = await Promise.race(promises); if (content === defaultResponse) { - traceWarning('Failed to Kernel info in a timely manner, defaulting to empty info!'); + logger.warn('Failed to Kernel info in a timely manner, defaulting to empty info!'); } else { - traceVerbose('Got Kernel info'); + logger.debug('Got Kernel info'); } return content; } diff --git a/src/kernels/kernelProvider.base.ts b/src/kernels/kernelProvider.base.ts index 93e7cf89cbd..67705529d20 100644 --- a/src/kernels/kernelProvider.base.ts +++ b/src/kernels/kernelProvider.base.ts @@ -3,7 +3,7 @@ import type { KernelMessage } from '@jupyterlab/services'; import { Event, EventEmitter, NotebookDocument, Uri, workspace } from 'vscode'; -import { traceInfoIfCI, traceVerbose, traceWarning } from '../platform/logging'; +import { logger } from '../platform/logging'; import { getDisplayPath } from '../platform/common/platform/fs-paths'; import { IAsyncDisposable, IAsyncDisposableRegistry, IDisposableRegistry } from '../platform/common/types'; import { isUri, noop } from '../platform/common/utils/misc'; @@ -99,7 +99,7 @@ export abstract class BaseCoreKernelProvider implements IKernelProvider { } public async dispose() { - traceInfoIfCI(`Disposing all kernels from kernel provider`); + logger.ci(`Disposing all kernels from kernel provider`); const items = Array.from(this.pendingDisposables.values()); this.pendingDisposables.clear(); await Promise.all(items); @@ -121,7 +121,7 @@ export abstract class BaseCoreKernelProvider implements IKernelProvider { if (this.get(kernel.notebook) === kernel) { this.kernelsByNotebook.delete(kernel.notebook); this.kernelsById.delete(kernel.id); - traceVerbose( + logger.debug( `Kernel got disposed, hence there is no longer a kernel associated with ${getDisplayPath( kernel.uri )}` @@ -136,14 +136,14 @@ export abstract class BaseCoreKernelProvider implements IKernelProvider { protected disposeOldKernel(notebook: NotebookDocument) { const kernelToDispose = this.kernelsByNotebook.get(notebook); if (kernelToDispose) { - traceVerbose( + logger.debug( `Disposing kernel associated with ${getDisplayPath(notebook.uri)}, isClosed=${notebook.isClosed}` ); this.kernelsById.delete(kernelToDispose.kernel.id); this.pendingDisposables.add(kernelToDispose.kernel); kernelToDispose.kernel .dispose() - .catch((ex) => traceWarning('Failed to dispose old kernel', ex)) + .catch((ex) => logger.warn('Failed to dispose old kernel', ex)) .finally(() => this.pendingDisposables.delete(kernelToDispose.kernel)) .catch(noop); } @@ -200,7 +200,7 @@ export abstract class BaseThirdPartyKernelProvider implements IThirdPartyKernelP this.asyncDisposables.push(this); workspace.onDidCloseNotebookDocument( (e) => { - traceVerbose(`Notebook document ${getDisplayPath(e.uri)} got closed`); + logger.debug(`Notebook document ${getDisplayPath(e.uri)} got closed`); this.disposeOldKernel(e.uri); }, this, @@ -239,7 +239,7 @@ export abstract class BaseThirdPartyKernelProvider implements IThirdPartyKernelP } public async dispose() { - traceInfoIfCI(`Disposing all kernels from kernel provider`); + logger.ci(`Disposing all kernels from kernel provider`); const items = Array.from(this.pendingDisposables.values()); this.pendingDisposables.clear(); await Promise.all(items); @@ -262,7 +262,7 @@ export abstract class BaseThirdPartyKernelProvider implements IThirdPartyKernelP if (this.get(uri) === kernel) { this.kernelsByUri.delete(uri.toString()); this.kernelsById.delete(kernel.id); - traceVerbose( + logger.debug( `Kernel got disposed, hence there is no longer a kernel associated with ${getDisplayPath(uri)}` ); } @@ -275,12 +275,12 @@ export abstract class BaseThirdPartyKernelProvider implements IThirdPartyKernelP protected disposeOldKernel(uri: Uri) { const kernelToDispose = this.kernelsByUri.get(uri.toString()); if (kernelToDispose) { - traceInfoIfCI(`Disposing kernel associated with ${getDisplayPath(uri)}`); + logger.ci(`Disposing kernel associated with ${getDisplayPath(uri)}`); this.kernelsById.delete(kernelToDispose.kernel.id); this.pendingDisposables.add(kernelToDispose.kernel); kernelToDispose.kernel .dispose() - .catch((ex) => traceWarning('Failed to dispose old kernel', ex)) + .catch((ex) => logger.warn('Failed to dispose old kernel', ex)) .finally(() => this.pendingDisposables.delete(kernelToDispose.kernel)) .catch(noop); } diff --git a/src/kernels/kernelRefreshIndicator.node.ts b/src/kernels/kernelRefreshIndicator.node.ts index f95789efa03..8f2857a827e 100644 --- a/src/kernels/kernelRefreshIndicator.node.ts +++ b/src/kernels/kernelRefreshIndicator.node.ts @@ -9,7 +9,7 @@ import { InteractiveWindowView, JupyterNotebookView } from '../platform/common/c import { dispose } from '../platform/common/utils/lifecycle'; import { IDisposable, IDisposableRegistry } from '../platform/common/types'; import { IInterpreterService } from '../platform/interpreter/contracts'; -import { traceVerbose } from '../platform/logging'; +import { logger } from '../platform/logging'; import { IKernelFinder } from './types'; import { isJupyterNotebook } from '../platform/common/utils'; import { noop } from '../platform/common/utils/misc'; @@ -57,7 +57,7 @@ export class KernelRefreshIndicator implements IExtensionSyncActivationService { const displayProgress = () => { const id = Date.now().toString(); - traceVerbose(`Start refreshing Kernel Picker (${id})`); + logger.debug(`Start refreshing Kernel Picker (${id})`); const taskNb = notebooks.createNotebookControllerDetectionTask(JupyterNotebookView); const taskIW = notebooks.createNotebookControllerDetectionTask(InteractiveWindowView); this.disposables.push(taskNb); @@ -66,7 +66,7 @@ export class KernelRefreshIndicator implements IExtensionSyncActivationService { this.kernelFinder.onDidChangeStatus( () => { if (this.kernelFinder.status === 'idle') { - traceVerbose(`End refreshing Kernel Picker (${id})`); + logger.debug(`End refreshing Kernel Picker (${id})`); taskNb.dispose(); taskIW.dispose(); } @@ -104,7 +104,7 @@ export class KernelRefreshIndicator implements IExtensionSyncActivationService { (e) => { if (!refreshedInterpreters && e && isJupyterNotebook(e.notebook)) { refreshedInterpreters = true; - traceVerbose(`Start refreshing Interpreter Kernel Picker`); + logger.debug(`Start refreshing Interpreter Kernel Picker`); this.interpreterService.refreshInterpreters().catch(noop); } }, @@ -115,7 +115,7 @@ export class KernelRefreshIndicator implements IExtensionSyncActivationService { (e) => { if (!refreshedInterpreters && isJupyterNotebook(e)) { refreshedInterpreters = true; - traceVerbose(`Start refreshing Interpreter Kernel Picker`); + logger.debug(`Start refreshing Interpreter Kernel Picker`); this.interpreterService.refreshInterpreters().catch(noop); } }, @@ -130,7 +130,7 @@ export class KernelRefreshIndicator implements IExtensionSyncActivationService { return kernelProgress; } id = Date.now().toString(); - traceVerbose(`Start refreshing Kernel Picker (${id})`); + logger.debug(`Start refreshing Kernel Picker (${id})`); kernelProgress = new DisposableStore( notebooks.createNotebookControllerDetectionTask(JupyterNotebookView), notebooks.createNotebookControllerDetectionTask(InteractiveWindowView) @@ -140,7 +140,7 @@ export class KernelRefreshIndicator implements IExtensionSyncActivationService { }; if (this.kernelFinder.status === 'idle') { - traceVerbose(`End refreshing Kernel Picker (${id})`); + logger.debug(`End refreshing Kernel Picker (${id})`); kernelProgress?.dispose(); } else { createProgressIndicator(); @@ -148,7 +148,7 @@ export class KernelRefreshIndicator implements IExtensionSyncActivationService { this.kernelFinder.onDidChangeStatus( () => { if (this.kernelFinder.status === 'idle') { - traceVerbose(`End refreshing Kernel Picker (${id})`); + logger.debug(`End refreshing Kernel Picker (${id})`); kernelProgress?.dispose(); } else { createProgressIndicator(); diff --git a/src/kernels/kernelRefreshIndicator.web.ts b/src/kernels/kernelRefreshIndicator.web.ts index f9351874cd0..90226393d2f 100644 --- a/src/kernels/kernelRefreshIndicator.web.ts +++ b/src/kernels/kernelRefreshIndicator.web.ts @@ -7,7 +7,7 @@ import { IExtensionSyncActivationService } from '../platform/activation/types'; import { InteractiveWindowView, JupyterNotebookView } from '../platform/common/constants'; import { dispose } from '../platform/common/utils/lifecycle'; import { IDisposable, IDisposableRegistry } from '../platform/common/types'; -import { traceVerbose } from '../platform/logging'; +import { logger } from '../platform/logging'; import { IKernelFinder } from './types'; /** * Ensures we refresh the list of Python environments upon opening a Notebook. @@ -54,7 +54,7 @@ export class KernelRefreshIndicator implements IExtensionSyncActivationService { } private displayProgressIndicator() { const id = Date.now().toString(); - traceVerbose(`Start refreshing Kernel Picker (${id})`); + logger.debug(`Start refreshing Kernel Picker (${id})`); const taskNb = notebooks.createNotebookControllerDetectionTask(JupyterNotebookView); const taskIW = notebooks.createNotebookControllerDetectionTask(InteractiveWindowView); this.disposables.push(taskNb); @@ -63,7 +63,7 @@ export class KernelRefreshIndicator implements IExtensionSyncActivationService { this.kernelFinder.onDidChangeStatus( () => { if (this.kernelFinder.status === 'idle') { - traceVerbose(`End refreshing Kernel Picker (${id})`); + logger.debug(`End refreshing Kernel Picker (${id})`); taskNb.dispose(); taskIW.dispose(); } diff --git a/src/kernels/raw/finder/contributedLocalKernelSpecFinder.node.ts b/src/kernels/raw/finder/contributedLocalKernelSpecFinder.node.ts index ce79c35746d..eb4b4522339 100644 --- a/src/kernels/raw/finder/contributedLocalKernelSpecFinder.node.ts +++ b/src/kernels/raw/finder/contributedLocalKernelSpecFinder.node.ts @@ -5,7 +5,7 @@ import { inject, injectable } from 'inversify'; import { EventEmitter, extensions } from 'vscode'; import { IKernelFinder, LocalKernelConnectionMetadata } from '../../types'; import { LocalKnownPathKernelSpecFinder } from './localKnownPathKernelSpecFinder.node'; -import { traceDecoratorError, traceError } from '../../../platform/logging'; +import { errorDecorator, logger } from '../../../platform/logging'; import { IDisposableRegistry } from '../../../platform/common/types'; import { areObjectsWithUrisTheSame } from '../../../platform/common/utils/misc'; import { KernelFinder } from '../../kernelFinder'; @@ -137,7 +137,7 @@ export class ContributedLocalKernelSpecFinder await promise; } - @traceDecoratorError('List kernels failed') + @errorDecorator('List kernels failed') private updateCache() { try { let kernels: LocalKernelConnectionMetadata[] = []; @@ -156,7 +156,7 @@ export class ContributedLocalKernelSpecFinder kernels = kernels.concat(kernelSpecs).concat(kernelSpecsFromPythonKernelFinder); this.writeToCache(kernels); } catch (ex) { - traceError('Exception Saving loaded kernels', ex); + logger.error('Exception Saving loaded kernels', ex); } } public get kernels(): LocalKernelConnectionMetadata[] { diff --git a/src/kernels/raw/finder/interpreterKernelSpecFinderHelper.node.ts b/src/kernels/raw/finder/interpreterKernelSpecFinderHelper.node.ts index ba0d484b20e..ee25730735e 100644 --- a/src/kernels/raw/finder/interpreterKernelSpecFinderHelper.node.ts +++ b/src/kernels/raw/finder/interpreterKernelSpecFinderHelper.node.ts @@ -21,7 +21,7 @@ import { LocalKernelSpecFinder } from './localKernelSpecFinderBase.node'; import { baseKernelPath, JupyterPaths } from './jupyterPaths.node'; import { IPythonExtensionChecker } from '../../../platform/api/types'; import { PYTHON_LANGUAGE, Telemetry } from '../../../platform/common/constants'; -import { traceVerbose, traceError, traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { getDisplayPath } from '../../../platform/common/platform/fs-paths.node'; import { IInterpreterService } from '../../../platform/interpreter/contracts'; import { areInterpreterPathsSame } from '../../../platform/pythonEnvironments/info/interpreter'; @@ -60,7 +60,7 @@ export async function findKernelSpecsInInterpreter( // Find all the possible places to look for this resource const sysPrefix = await getSysPrefix(interpreter); if (!sysPrefix) { - traceWarning(`Failed to get sysPrefix for interpreter ${getDisplayPath(interpreter.id)}`); + logger.warn(`Failed to get sysPrefix for interpreter ${getDisplayPath(interpreter.id)}`); return; } const kernelSearchPath = Uri.file(path.join(sysPrefix, baseKernelPath)); @@ -123,7 +123,7 @@ export async function findKernelSpecsInInterpreter( emitter.fire(kernelSpec); } } catch (ex) { - traceError(`Failed to load kernel spec ${kernelSpecFile}`, ex); + logger.error(`Failed to load kernel spec ${kernelSpecFile}`, ex); } }) ); @@ -179,7 +179,7 @@ export class InterpreterSpecificKernelSpecsFinder extends DisposableBase { void this.kernelSpecPromise.then(() => { switch (this._kernels.size) { case 0: - traceVerbose(`No Kernels found in interpreter ${this.interpreter.id}`); + logger.debug(`No Kernels found in interpreter ${this.interpreter.id}`); break; case 1: // Thats the default kernel we create for this interpreter. @@ -187,7 +187,7 @@ export class InterpreterSpecificKernelSpecsFinder extends DisposableBase { // No need to log this, just noise. It will be an obvious entry break; default: - traceVerbose( + logger.debug( `Kernels for interpreter ${this.interpreter.id} are ${Array.from(this._kernels.keys()).join( ', ' )}` @@ -223,7 +223,7 @@ export class InterpreterSpecificKernelSpecsFinder extends DisposableBase { return; } - traceVerbose(`Search for KernelSpecs in Interpreter ${getDisplayPath(this.interpreter.uri)}`); + logger.debug(`Search for KernelSpecs in Interpreter ${getDisplayPath(this.interpreter.uri)}`); // If the user has interpreters, then don't display the default kernel specs such as `python`, `python3`. // Such kernel specs are ambiguous, and we have absolutely no idea what interpreters they point to. @@ -245,7 +245,7 @@ export class InterpreterSpecificKernelSpecsFinder extends DisposableBase { (!jupyterKernelSpec.env || Object.keys(jupyterKernelSpec.env).length === 0) && isDefaultKernelSpec(jupyterKernelSpec) ) { - traceVerbose( + logger.debug( `Hiding default KernelSpec ${getDisplayPath( jupyterKernelSpec.argv[0] )} for interpreter ${getDisplayPath( @@ -410,7 +410,7 @@ export class GlobalPythonKernelSpecFinder implements IDisposable { kernelSpec.metadata?.interpreter?.path && areInterpreterPathsSame(Uri.file(kernelSpec.metadata.interpreter.path), i.executable.uri) ) { - traceVerbose( + logger.debug( `Kernel ${kernelSpec.name} matches ${getDisplayPath(i.id)} based on metadata.interpreter.` ); return true; @@ -435,7 +435,7 @@ export class GlobalPythonKernelSpecFinder implements IDisposable { const pathInArgVUri = Uri.file(pathInArgv); const exactMatchBasedOnArgv = interpreters.find((i) => { if (areInterpreterPathsSame(pathInArgVUri, i.executable.uri)) { - traceVerbose(`Kernel ${kernelSpec.name} matches ${getDisplayPath(i.id)} based on argv.`); + logger.debug(`Kernel ${kernelSpec.name} matches ${getDisplayPath(i.id)} based on argv.`); return true; } return false; @@ -512,7 +512,7 @@ export class GlobalPythonKernelSpecFinder implements IDisposable { kernelSpec.interpreterPath && areInterpreterPathsSame(kernelSpecInterpreterPath, i.executable.uri) ) { - traceVerbose(`Kernel ${kernelSpec.name} matches ${getDisplayPath(i.id)} based on interpreterPath.`); + logger.debug(`Kernel ${kernelSpec.name} matches ${getDisplayPath(i.id)} based on interpreterPath.`); return true; } return false; @@ -539,7 +539,7 @@ export class GlobalPythonKernelSpecFinder implements IDisposable { interpreters.find((i) => { // 4. Check display name if (kernelSpec.display_name === getCachedEnvironment(i)?.environment?.name) { - traceVerbose(`Kernel ${kernelSpec.name} matches ${getDisplayPath(i.id)} based on display name`); + logger.debug(`Kernel ${kernelSpec.name} matches ${getDisplayPath(i.id)} based on display name`); // This is a bad one, matching by name is never going to be accurate sendTelemetryEvent(Telemetry.AmbiguousGlobalKernelSpec, undefined, { kernelSpecHash, @@ -569,7 +569,7 @@ export class GlobalPythonKernelSpecFinder implements IDisposable { return; } GlobalPythonKernelSpecFinder.globalPythonKernelSpecsForWhichWeCouldNotFindInterpreterInfo.add(key); - traceWarning( + logger.warn( `Kernel Spec for '${kernelSpec.display_name}' (${getDisplayPath( kernelSpec.specFile )}) hidden, as we cannot find a matching interpreter argv = '${ @@ -590,7 +590,7 @@ export class GlobalPythonKernelSpecFinder implements IDisposable { // (workspace.workspaceFolders || []).map((folder) => this.interpreterService.getActiveInterpreter(folder.uri)) // ); - // traceVerbose(`Finding Global Python KernelSpecs`); + // logger.debug(`Finding Global Python KernelSpecs`); // const activeInterpreters = await raceCancellation(cancelToken, [], activeInterpreterInAWorkspacePromise); // if (cancelToken.isCancellationRequested) { // return []; @@ -642,7 +642,7 @@ export class GlobalPythonKernelSpecFinder implements IDisposable { ) { return true; } - traceVerbose( + logger.debug( `Kernel Spec for '${item.kernelSpec.display_name}' (${getDisplayPath( item.kernelSpec.specFile )}) is hidden. (isDefaultKernelSpec = ${isDefaultKernelSpec(item.kernelSpec)}, language = ${ @@ -701,7 +701,7 @@ export class GlobalPythonKernelSpecFinder implements IDisposable { // (!kernelSpec.env || Object.keys(kernelSpec.env).length === 0) && // isDefaultKernelSpec(kernelSpec) // ) { - // traceVerbose( + // logger.debug( // `Hiding default kernel spec '${kernelSpec.display_name}', '${ // kernelSpec.name // }', ${getDisplayPath(kernelSpec.argv[0])} for interpreter ${getDisplayPath( @@ -711,7 +711,7 @@ export class GlobalPythonKernelSpecFinder implements IDisposable { // return false; // } // if (kernelSpec.specFile && globalKernelSpecsLoadedForPython.has(kernelSpec.specFile)) { - // traceVerbose( + // logger.debug( // `Global kernel spec ${kernelSpec.name}${getDisplayPath( // kernelSpec.specFile // )} already found with a matching Python Env` @@ -720,7 +720,7 @@ export class GlobalPythonKernelSpecFinder implements IDisposable { // } // // Check if this is a kernelspec registered by an old version of the extension. // if (getKernelRegistrationInfo(kernelSpec) === 'registeredByOldVersionOfExt') { - // traceVerbose( + // logger.debug( // `Ignoring Global Python KernelSpec '${kernelSpec.display_name}', '${ // kernelSpec.name // }' (${getDisplayPath(kernelSpec.specFile)}) registered by an old version of the extension` @@ -754,7 +754,7 @@ export class GlobalPythonKernelSpecFinder implements IDisposable { // id: getKernelId(k, matchingInterpreter) // }); - // traceInfo( + // logger.info( // `Using interpreter ${getDisplayPath(matchingInterpreter.id)} for Global Python kernel '${ // k.display_name // }', ${k.name} (${getDisplayPath(k.specFile)})` @@ -801,7 +801,7 @@ export class GlobalPythonKernelSpecFinder implements IDisposable { // ); // foundRightInterpreter = !!kernelInterpreter; // } catch (ex) { - // traceError( + // logger.error( // `Failed to get interpreter details for Kernel Spec '${k.display_name}', '${ // k.name // }' ${getDisplayPathFromLocalFile( @@ -817,7 +817,7 @@ export class GlobalPythonKernelSpecFinder implements IDisposable { // activeInterpreterOfAWorkspaceFolder === kernelInterpreter && // !foundRightInterpreter // ) { - // traceWarning( + // logger.warn( // `Kernel might not start correctly: Fully qualified Python exe not defined (or not found) in Kernel Spec ${ // k.id // } (${getDisplayPathFromLocalFile( @@ -829,7 +829,7 @@ export class GlobalPythonKernelSpecFinder implements IDisposable { // )}` // ); // } else if (!foundRightInterpreter) { - // traceWarning( + // logger.warn( // `Kernel might not start correctly: Fully qualified Python exe not defined (or not found) in Kernel Spec ${ // k.id // } (${getDisplayPathFromLocalFile( @@ -842,7 +842,7 @@ export class GlobalPythonKernelSpecFinder implements IDisposable { // interpreter: kernelInterpreter, // id: getKernelId(k, kernelInterpreter) // }); - // traceVerbose(`Interpreter for Local kernel ${result.id} is ${kernelInterpreter?.id}`); + // logger.debug(`Interpreter for Local kernel ${result.id} is ${kernelInterpreter?.id}`); // return result; // } @@ -853,7 +853,7 @@ export class GlobalPythonKernelSpecFinder implements IDisposable { // } // const kernelSpec = await item; - // traceVerbose(`Found kernel spec at end of discovery ${kernelSpec?.id}`); + // logger.debug(`Found kernel spec at end of discovery ${kernelSpec?.id}`); // // Check if we have already seen this. // if (kernelSpec && !distinctKernelMetadata.has(kernelSpec.id)) { // distinctKernelMetadata.set(kernelSpec.id, kernelSpec); diff --git a/src/kernels/raw/finder/jupyterPaths.node.ts b/src/kernels/raw/finder/jupyterPaths.node.ts index ec1fbd61aaf..d00315319be 100644 --- a/src/kernels/raw/finder/jupyterPaths.node.ts +++ b/src/kernels/raw/finder/jupyterPaths.node.ts @@ -7,14 +7,7 @@ import * as uriPath from '../../../platform/vscode-path/resources'; import { CancellationToken, Memento, Uri } from 'vscode'; import { IFileSystem, IPlatformService } from '../../../platform/common/platform/types'; import { IFileSystemNode } from '../../../platform/common/platform/types.node'; -import { - ignoreLogging, - logValue, - traceError, - traceInfoIfCI, - traceVerbose, - traceWarning -} from '../../../platform/logging'; +import { ignoreLogging, logValue, logger } from '../../../platform/logging'; import { IDisposableRegistry, IMemento, @@ -24,7 +17,7 @@ import { } from '../../../platform/common/types'; import { tryGetRealPath } from '../../../platform/common/utils.node'; import { ICustomEnvironmentVariablesProvider } from '../../../platform/common/variables/types'; -import { traceDecoratorVerbose } from '../../../platform/logging'; +import { debugDecorator } from '../../../platform/logging'; import { OSType } from '../../../platform/common/utils/platform.node'; import { noop } from '../../../platform/common/utils/misc'; import { PythonEnvironment } from '../../../platform/pythonEnvironments/info'; @@ -108,7 +101,7 @@ export class JupyterPaths { })(); this.cachedKernelSpecRootPath .then((value) => { - traceVerbose(`Getting Jupyter KernelSpec Root Path ${value?.toString()}`); + logger.debug(`Getting Jupyter KernelSpec Root Path ${value?.toString()}`); this.updateCachedRootPath(value); }) .catch(noop); @@ -135,7 +128,7 @@ export class JupyterPaths { } } if (!runtimeDir) { - traceError(`Failed to determine Jupyter runtime directory`); + logger.error(`Failed to determine Jupyter runtime directory`); return; } @@ -144,7 +137,7 @@ export class JupyterPaths { await this.fs.createDirectory(runtimeDir); return runtimeDir; } catch (ex) { - traceError(`Failed to create runtime directory, reverting to temp directory ${runtimeDir}`, ex); + logger.error(`Failed to create runtime directory, reverting to temp directory ${runtimeDir}`, ex); } } /** @@ -160,10 +153,7 @@ export class JupyterPaths { return this.cachedDataDirs.get(key)!; } - @traceDecoratorVerbose( - 'getDataDirsImpl', - TraceOptions.BeforeCall | TraceOptions.Arguments | TraceOptions.ReturnValue - ) + @debugDecorator('getDataDirsImpl', TraceOptions.BeforeCall | TraceOptions.Arguments | TraceOptions.ReturnValue) private async getDataDirsImpl( resource: Resource, @logValue('id') interpreter?: PythonEnvironment @@ -182,7 +172,7 @@ export class JupyterPaths { // 2. Add the paths based on ENABLE_USER_SITE if (interpreter) { try { - traceInfoIfCI(`Getting Jupyter Data Dir for ${interpreter.uri.fsPath}`); + logger.ci(`Getting Jupyter Data Dir for ${interpreter.uri.fsPath}`); const factory = await this.pythonExecFactory.createActivatedEnvironment({ interpreter, resource @@ -197,10 +187,10 @@ export class JupyterPaths { } } } else { - traceWarning(`Got an empty Jupyter Data Dir from ${interpreter.id}, stderr = ${result.stderr}`); + logger.warn(`Got an empty Jupyter Data Dir from ${interpreter.id}, stderr = ${result.stderr}`); } } catch (ex) { - traceError( + logger.error( `Failed to get DataDir based on ENABLE_USER_SITE for ${getPythonEnvDisplayName(interpreter)}`, ex ); @@ -343,7 +333,7 @@ export class JupyterPaths { } } - traceVerbose( + logger.debug( `Kernel Spec Root Paths, ${Array.from(paths) .map((uri) => getDisplayPath(uri)) .join(', ')}` @@ -396,7 +386,7 @@ export class JupyterPaths { }); } - traceVerbose(`Jupyter Paths ${getDisplayPath(subDir)}: ${Array.from(paths).map((uri) => getDisplayPath(uri))}`); + logger.debug(`Jupyter Paths ${getDisplayPath(subDir)}: ${Array.from(paths).map((uri) => getDisplayPath(uri))}`); return Array.from(paths); } diff --git a/src/kernels/raw/finder/localKernelSpecFinderBase.node.ts b/src/kernels/raw/finder/localKernelSpecFinderBase.node.ts index b95e6419dbe..ef74a89abbe 100644 --- a/src/kernels/raw/finder/localKernelSpecFinderBase.node.ts +++ b/src/kernels/raw/finder/localKernelSpecFinderBase.node.ts @@ -7,7 +7,7 @@ import { CancellationToken, Disposable, Event, EventEmitter, Memento, Uri } from import { IPythonExtensionChecker } from '../../../platform/api/types'; import { IApplicationEnvironment } from '../../../platform/common/application/types'; import { PYTHON_LANGUAGE } from '../../../platform/common/constants'; -import { traceVerbose, traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { getDisplayPath } from '../../../platform/common/platform/fs-paths'; import { IFileSystemNode } from '../../../platform/common/platform/types.node'; import { IDisposable, IDisposableRegistry, ReadWrite } from '../../../platform/common/types'; @@ -57,7 +57,7 @@ export class LocalKernelSpecFinder implements IDisposable { private readonly jupyterPaths: JupyterPaths ) { if (this.oldKernelSpecsFolder) { - traceVerbose( + logger.debug( `Old kernelSpecs (created by Jupyter Extension) stored in directory ${this.oldKernelSpecsFolder}` ); } @@ -131,7 +131,7 @@ export class LocalKernelSpecFinder implements IDisposable { await this.fs.createDirectory(Uri.file(path.dirname(destinationFile))); await this.fs.copy(Uri.file(kernelSpecFile), Uri.file(destinationFile)).catch(noop); await this.fs.delete(Uri.file(kernelSpecFile)); - traceVerbose(`Old KernelSpec '${kernelSpecFile}' deleted and backup stored in ${destinationFolder}`); + logger.debug(`Old KernelSpec '${kernelSpecFile}' deleted and backup stored in ${destinationFolder}`); } /** * Load kernelspec json from disk @@ -180,7 +180,7 @@ export class LocalKernelSpecFinder implements IDisposable { if (this.findKernelSpecsInPathCache.get(cacheKey) === promise) { this.findKernelSpecsInPathCache.delete(cacheKey); } - traceVerbose(`Failed to search for kernels in ${getDisplayPath(kernelSearchPath)} with an error`, ex); + logger.debug(`Failed to search for kernels in ${getDisplayPath(kernelSearchPath)} with an error`, ex); }); return promise; } @@ -330,14 +330,14 @@ export async function loadKernelSpec( } let kernelJson: ReadWrite; try { - // traceVerbose( + // logger.debug( // `Loading kernelspec from ${getDisplayPath(specPath)} ${ // interpreter?.uri ? `for ${getDisplayPath(interpreter.uri)}` : '' // }` // ); kernelJson = JSON.parse(await fs.readFile(specPath)); } catch (ex) { - traceError(`Failed to parse kernelspec ${specPath}`, ex); + logger.error(`Failed to parse kernelspec ${specPath}`, ex); return; } if (cancelToken.isCancellationRequested) { diff --git a/src/kernels/raw/finder/localKnownPathKernelSpecFinder.node.ts b/src/kernels/raw/finder/localKnownPathKernelSpecFinder.node.ts index 8e402ec9c3b..4b700190d17 100644 --- a/src/kernels/raw/finder/localKnownPathKernelSpecFinder.node.ts +++ b/src/kernels/raw/finder/localKnownPathKernelSpecFinder.node.ts @@ -9,7 +9,7 @@ import { LocalKernelSpecFinderBase } from './localKernelSpecFinderBase.node'; import { JupyterPaths } from './jupyterPaths.node'; import { IPythonExtensionChecker } from '../../../platform/api/types'; import { IApplicationEnvironment } from '../../../platform/common/application/types'; -import { traceError, traceVerbose, traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IFileSystemNode } from '../../../platform/common/platform/types.node'; import { IMemento, GLOBAL_MEMENTO, IDisposableRegistry } from '../../../platform/common/types'; import { sendKernelSpecTelemetry } from './helper'; @@ -90,7 +90,7 @@ export class LocalKnownPathKernelSpecFinder newKernelSpecs.forEach((k) => this._kernels.set(k.id, k)); if (deletedKernels.length) { - traceVerbose( + logger.debug( `Local kernel spec connection deleted ${deletedKernels.map((item) => `${item.kind}:'${item.id}'`)}` ); deletedKernels.forEach((k) => this._kernels.delete(k.id)); @@ -177,12 +177,12 @@ export class LocalKnownPathKernelSpecFinder this.writeKernelsToMemento(); } } else { - traceWarning( + logger.warn( `Duplicate kernel found ${kernelSpec.display_name} ${kernelSpec.executable} in ${kernelSpec.specFile}` ); } } catch (ex) { - traceError(`Failed to load kernelSpec for ${kernelSpecFile}`, ex); + logger.error(`Failed to load kernelSpec for ${kernelSpecFile}`, ex); return; } }) diff --git a/src/kernels/raw/finder/localPythonAndRelatedNonPythonKernelSpecFinder.node.ts b/src/kernels/raw/finder/localPythonAndRelatedNonPythonKernelSpecFinder.node.ts index 19c2ec75d48..acb88b9402f 100644 --- a/src/kernels/raw/finder/localPythonAndRelatedNonPythonKernelSpecFinder.node.ts +++ b/src/kernels/raw/finder/localPythonAndRelatedNonPythonKernelSpecFinder.node.ts @@ -11,7 +11,7 @@ import { LocalKnownPathKernelSpecFinder } from './localKnownPathKernelSpecFinder import { IPythonExtensionChecker } from '../../../platform/api/types'; import { IApplicationEnvironment } from '../../../platform/common/application/types'; import { PYTHON_LANGUAGE } from '../../../platform/common/constants'; -import { traceVerbose, traceError, traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IFileSystemNode } from '../../../platform/common/platform/types.node'; import { IMemento, IDisposableRegistry, WORKSPACE_MEMENTO } from '../../../platform/common/types'; import { IInterpreterService } from '../../../platform/interpreter/contracts'; @@ -102,11 +102,11 @@ export class LocalPythonAndRelatedNonPythonKernelSpecFinder extends LocalKernelS return; } - traceVerbose(`Interpreter removed ${e.id}`); + logger.debug(`Interpreter removed ${e.id}`); const deletedKernels: LocalKernelConnectionMetadata[] = []; this._kernels.forEach((k) => { if (k.interpreter?.id === e.id) { - traceVerbose( + logger.debug( `Interpreter ${e.id} deleted, hence deleting corresponding kernel ${k.kind}:'${k.id}` ); deletedKernels.push(k); @@ -114,7 +114,7 @@ export class LocalPythonAndRelatedNonPythonKernelSpecFinder extends LocalKernelS } }); if (deletedKernels.length) { - traceVerbose( + logger.debug( `Local Python connection deleted ${deletedKernels.map( (item) => `${item.kind}:'${item.id}: (interpreter id=${getDisplayPath(item.interpreter?.id)})'` @@ -197,7 +197,7 @@ export class LocalPythonAndRelatedNonPythonKernelSpecFinder extends LocalKernelS const cancelToken = (this.refreshCancellation = new CancellationTokenSource()); const promise = (async () => { await this.listKernelsImplementation(cancelToken.token, forcePythonInterpreterRefresh).catch((ex) => - traceError('Failure in listKernelsImplementation', ex) + logger.error('Failure in listKernelsImplementation', ex) ); if (cancelToken.token.isCancellationRequested) { return; @@ -211,7 +211,7 @@ export class LocalPythonAndRelatedNonPythonKernelSpecFinder extends LocalKernelS ); const deletedKernels: LocalKernelConnectionMetadata[] = []; if (kernelConnectionsFoundOnlyInCache.length) { - traceWarning( + logger.warn( `Kernels ${kernelConnectionsFoundOnlyInCache .map((item) => `${item.kind}:'${item.id}'`) .join(', ')} found in cache but not discovered in current session ${Array.from( @@ -238,7 +238,7 @@ export class LocalPythonAndRelatedNonPythonKernelSpecFinder extends LocalKernelS return false; }); if (kernelsThatPointToInvalidValidInterpreters.length) { - traceWarning( + logger.warn( `The following kernels use interpreters that are no longer valid or not recognized by Python extension, Kernels ${kernelsThatPointToInvalidValidInterpreters .map( (item) => @@ -255,7 +255,7 @@ export class LocalPythonAndRelatedNonPythonKernelSpecFinder extends LocalKernelS } if (deletedKernels.length) { - traceVerbose( + logger.debug( `Local Python connection deleted ${deletedKernels.map( (item) => `${item.kind}:'${item.id}: (interpreter id=${getDisplayPath(item.interpreter?.id)})'` @@ -269,7 +269,7 @@ export class LocalPythonAndRelatedNonPythonKernelSpecFinder extends LocalKernelS this._kernelsFromCache = []; } })() - .catch((ex) => traceError(`Failed to discover kernels in interpreters`, ex)) + .catch((ex) => logger.error(`Failed to discover kernels in interpreters`, ex)) .finally(() => { if (cancelToken === this.refreshCancellation) { this.refreshCancellation?.cancel(); @@ -350,7 +350,7 @@ export class LocalPythonAndRelatedNonPythonKernelSpecFinder extends LocalKernelS this._kernels.set(kernel.id, kernel); } } else { - traceWarning(`Found a kernel ${kernel.kind}:'${kernel.id}', but excluded as specFile is undefined`); + logger.warn(`Found a kernel ${kernel.kind}:'${kernel.id}', but excluded as specFile is undefined`); } }); diff --git a/src/kernels/raw/finder/localPythonAndRelatedNonPythonKernelSpecFinder.node.unit.test.ts b/src/kernels/raw/finder/localPythonAndRelatedNonPythonKernelSpecFinder.node.unit.test.ts index 3cde1e804d1..7be33a3bcf4 100644 --- a/src/kernels/raw/finder/localPythonAndRelatedNonPythonKernelSpecFinder.node.unit.test.ts +++ b/src/kernels/raw/finder/localPythonAndRelatedNonPythonKernelSpecFinder.node.unit.test.ts @@ -25,7 +25,7 @@ import { noop } from '../../../platform/common/utils/misc'; import { createInterpreterKernelSpec, getKernelId } from '../../helpers'; import { deserializePythonEnvironment, serializePythonEnvironment } from '../../../platform/api/pythonApi'; import { uriEquals } from '../../../test/datascience/helpers'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { sleep } from '../../../test/core'; import { localPythonKernelsCacheKey } from './interpreterKernelSpecFinderHelper.node'; import { mockedVSCodeNamespaces } from '../../../test/vscode-mock'; @@ -78,7 +78,7 @@ suite(`Local Python and related kernels`, async () => { let environments: PythonExtension['environments']; setup(async function () { - traceInfo(`Start Test (started) ${this.currentTest?.title}`); + logger.info(`Start Test (started) ${this.currentTest?.title}`); interpreterService = mock(); fs = mock(); jupyterPaths = mock(); @@ -254,10 +254,10 @@ suite(`Local Python and related kernels`, async () => { ); }); disposables.push(new Disposable(() => loadKernelSpecStub.restore())); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); await dispose(disposables); }); diff --git a/src/kernels/raw/finder/pythonKernelInterruptDaemon.node.ts b/src/kernels/raw/finder/pythonKernelInterruptDaemon.node.ts index 0dadce5ec06..880483ddacc 100644 --- a/src/kernels/raw/finder/pythonKernelInterruptDaemon.node.ts +++ b/src/kernels/raw/finder/pythonKernelInterruptDaemon.node.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { traceError, traceInfoIfCI, traceVerbose, traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { ObservableExecutionResult } from '../../../platform/common/process/types.node'; import { EnvironmentType, PythonEnvironment } from '../../../platform/pythonEnvironments/info'; import { inject, injectable } from 'inversify'; @@ -80,7 +80,7 @@ export class PythonKernelInterruptDaemon { try { return await this.createInterrupterImpl(pythonEnvironment, resource); } catch (ex) { - traceError(`Failed to create interrupter, trying again`, ex); + logger.error(`Failed to create interrupter, trying again`, ex); return this.createInterrupterImpl(pythonEnvironment, resource); } } @@ -94,7 +94,7 @@ export class PythonKernelInterruptDaemon { resource )) as number; if (!interruptHandle) { - traceError(`Unable to initialize interrupt handle`); + logger.error(`Unable to initialize interrupt handle`); throw new Error(`Unable to initialize interrupt handle`); } @@ -108,7 +108,7 @@ export class PythonKernelInterruptDaemon { { command: 'DISPOSE_INTERRUPT_HANDLE', handle: interruptHandle }, pythonEnvironment, resource - ).catch((ex) => traceError(`Failed to dispose interrupt handle for ${pythonEnvironment.id}`, ex)); + ).catch((ex) => logger.error(`Failed to dispose interrupt handle for ${pythonEnvironment.id}`, ex)); } }; } @@ -147,7 +147,7 @@ export class PythonKernelInterruptDaemon { await new Promise((resolve, reject) => { let started = false; const subscription = proc.out.onDidChange((out) => { - traceInfoIfCI( + logger.ci( `Output from interrupt daemon started = ${started}, output (${out.source}) = ${out.out} ('END)` ); if (out.source === 'stdout' && out.out.trim().includes('DAEMON_STARTED:') && !started) { @@ -167,14 +167,14 @@ export class PythonKernelInterruptDaemon { const id = parseInt(parts[parts.indexOf('INITIALIZE_INTERRUPT') + 1], 10); const deferred = this.messages.get(id); if (deferred) { - traceError(`Failed to initialize interrupt daemon for ${id}, ${out.out}`); + logger.error(`Failed to initialize interrupt daemon for ${id}, ${out.out}`); deferred.deferred.reject( new Error(`Failed to start interrupt daemon ${out.out}`) ); this.messages.delete(id); } } catch (ex) { - traceError(`Failed to parse interrupt daemon response, ${out.out}`, ex); + logger.error(`Failed to parse interrupt daemon response, ${out.out}`, ex); } }); } else if (out.source === 'stdout' && out.out.includes('INTERRUPT:') && started) { @@ -185,20 +185,20 @@ export class PythonKernelInterruptDaemon { const [command, id, response] = output.split(':'); const deferred = this.messages.get(parseInt(id, 10)); if (deferred) { - traceVerbose(`Got a response of ${response} for ${command}:${id}`); + logger.debug(`Got a response of ${response} for ${command}:${id}`); deferred.deferred.resolve(response); this.messages.delete(parseInt(id, 10)); } else { - traceError( + logger.error( `Got a response of ${response} for ${command}:${id} but no command entry found in ${out.out}` ); } } catch (ex) { - traceError(`Failed to parse interrupt daemon response, ${out.out}`, ex); + logger.error(`Failed to parse interrupt daemon response, ${out.out}`, ex); } }); } else if (out.out.includes('ERROR: handling command')) { - traceWarning(`Error output in interrupt daemon response ${out.out} ('END')`); + logger.warn(`Error output in interrupt daemon response ${out.out} ('END')`); if (!started) { return reject(new Error(`Interrupt daemon failed to start, ${out.out}`)); } @@ -211,7 +211,7 @@ export class PythonKernelInterruptDaemon { return; } } catch (ex) { - traceError(`Failed to parse interrupt daemon response, ${out.out}`, ex); + logger.error(`Failed to parse interrupt daemon response, ${out.out}`, ex); } } }); @@ -221,18 +221,18 @@ export class PythonKernelInterruptDaemon { // Added for logging to see if this process dies. // We can remove this later if there are no more flaky test failures. proc.proc?.on('close', () => { - traceInfoIfCI('Interrupt daemon closed'); + logger.ci('Interrupt daemon closed'); this.startupPromise = undefined; }); // Added for logging to see if this process dies. // We can remove this later if there are no more flaky test failures. proc.proc?.on('exit', () => { - traceInfoIfCI('Interrupt daemon exited'); + logger.ci('Interrupt daemon exited'); this.startupPromise = undefined; }); return proc; })(); - promise.catch((ex) => traceError(`Failed to start interrupt daemon for (${pythonEnvironment.id})`, ex)); + promise.catch((ex) => logger.error(`Failed to start interrupt daemon for (${pythonEnvironment.id})`, ex)); this.startupPromise = promise; return promise; } @@ -251,13 +251,13 @@ export class PythonKernelInterruptDaemon { const { proc } = await this.initializeInterrupter(pythonEnvironment, resource); if (!proc || !proc.stdin) { // An impossible scenario, but types in node.js requires this, and we need to check to keep the compiler happy - traceError('No process or stdin'); + logger.error('No process or stdin'); throw new Error('No process or stdin'); } proc.stdin.write(`${messageToSend}${EOL}`); - traceInfoIfCI(`Sending Interrupt Request id=${id}, Command ${command.command} for ${pythonEnvironment.id}`); + logger.ci(`Sending Interrupt Request id=${id}, Command ${command.command} for ${pythonEnvironment.id}`); const response = await deferred.promise; - traceInfoIfCI(`Got Interrupt Response id=${id}, Command ${command.command} for ${pythonEnvironment.id}`); + logger.ci(`Got Interrupt Response id=${id}, Command ${command.command} for ${pythonEnvironment.id}`); if (command.command === 'INITIALIZE_INTERRUPT') { return parseInt(response as string, 10); } diff --git a/src/kernels/raw/launcher/kernelEnvVarsService.node.ts b/src/kernels/raw/launcher/kernelEnvVarsService.node.ts index a64b351f299..a65ea714d7d 100644 --- a/src/kernels/raw/launcher/kernelEnvVarsService.node.ts +++ b/src/kernels/raw/launcher/kernelEnvVarsService.node.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { inject, injectable } from 'inversify'; -import { traceInfo, traceError, traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { getDisplayPath } from '../../../platform/common/platform/fs-paths'; import { IConfigurationService, Resource } from '../../../platform/common/types'; import { noop } from '../../../platform/common/utils/misc'; @@ -58,7 +58,7 @@ export class KernelEnvironmentVariablesService { interpreter = await this.interpreterService .getInterpreterDetails(Uri.file(kernelSpec.interpreterPath), token) .catch((ex) => { - traceError('Failed to fetch interpreter information for interpreter that owns a kernel', ex); + logger.error('Failed to fetch interpreter information for interpreter that owns a kernel', ex); return undefined; }); } @@ -73,7 +73,10 @@ export class KernelEnvironmentVariablesService { ? this.envActivation .getActivatedEnvironmentVariables(resource, interpreter, token) .catch((ex) => { - traceError('Failed to get env variables for interpreter, hence no variables for Kernel', ex); + logger.error( + 'Failed to get env variables for interpreter, hence no variables for Kernel', + ex + ); return undefined; }) : undefined @@ -86,7 +89,7 @@ export class KernelEnvironmentVariablesService { }); if (!interpreterEnv && Object.keys(customEnvVars || {}).length === 0) { - traceVerbose('No custom variables nor do we have a conda environment'); + logger.debug('No custom variables nor do we have a conda environment'); } let mergedVars = { ...process.env }; @@ -121,7 +124,7 @@ export class KernelEnvironmentVariablesService { // For more details see here https://github.com/microsoft/vscode-jupyter/issues/8553#issuecomment-997144591 // https://docs.python.org/3/library/site.html#site.ENABLE_USER_SITE if (this.configService.getSettings(undefined).excludeUserSitePackages) { - traceInfo(`Adding env Variable PYTHONNOUSERSITE to ${getDisplayPath(interpreter?.uri)}`); + logger.info(`Adding env Variable PYTHONNOUSERSITE to ${getDisplayPath(interpreter?.uri)}`); mergedVars.PYTHONNOUSERSITE = 'True'; } if (isPythonKernel) { @@ -165,7 +168,7 @@ function substituteEnvVars(key: string, value: string, globalVars: EnvironmentVa return globalVars[substName] || ''; }); if (!invalid && replacement !== value) { - traceVerbose(`${key} value in kernelSpec updated from ${value} to ${replacement}`); + logger.debug(`${key} value in kernelSpec updated from ${value} to ${replacement}`); value = replacement; } diff --git a/src/kernels/raw/launcher/kernelLauncher.node.ts b/src/kernels/raw/launcher/kernelLauncher.node.ts index 5f4428874c1..c78289caace 100644 --- a/src/kernels/raw/launcher/kernelLauncher.node.ts +++ b/src/kernels/raw/launcher/kernelLauncher.node.ts @@ -11,7 +11,7 @@ import { CancellationError, CancellationToken, window } from 'vscode'; import { IPythonExtensionChecker } from '../../../platform/api/types'; import { Cancellation, raceCancellationError } from '../../../platform/common/cancellation'; import { getTelemetrySafeErrorMessageFromPythonTraceback } from '../../../platform/errors/errorUtils'; -import { traceVerbose, traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { getDisplayPath } from '../../../platform/common/platform/fs-paths'; import { IFileSystemNode } from '../../../platform/common/platform/types.node'; import { IProcessServiceFactory } from '../../../platform/common/process/types.node'; @@ -82,7 +82,7 @@ export class KernelLauncher implements IKernelLauncher { portStart += 1_000; } } - traceVerbose(`Computed port start for KernelLauncher is : ${result}`); + logger.debug(`Computed port start for KernelLauncher is : ${result}`); return result; } else { @@ -267,20 +267,20 @@ async function logIPyKernelPath( .map((s) => s.trim()) .filter((s) => s.length > 0); if (outputs.length === 2) { - traceVerbose( + logger.debug( `ipykernel version & path ${outputs[0]}, ${getDisplayPathFromLocalFile( outputs[1] )} for ${displayInterpreterPath}` ); } else { - traceVerbose(`ipykernel version & path ${output.stdout.trim()} for ${displayInterpreterPath}`); + logger.debug(`ipykernel version & path ${output.stdout.trim()} for ${displayInterpreterPath}`); } } if (output.stderr) { const formattedOutput = splitLines(output.stderr.trim(), { removeEmptyEntries: true, trim: true }) .map((l, i) => (i === 0 ? l : ` ${l}`)) .join('\n'); - traceWarning( + logger.warn( `Stderr output when getting ipykernel version & path ${formattedOutput} for ${displayInterpreterPath}` ); } diff --git a/src/kernels/raw/launcher/kernelProcess.node.ts b/src/kernels/raw/launcher/kernelProcess.node.ts index f16d9bcd1a3..65c6555a515 100644 --- a/src/kernels/raw/launcher/kernelProcess.node.ts +++ b/src/kernels/raw/launcher/kernelProcess.node.ts @@ -26,14 +26,7 @@ import { getErrorMessageFromPythonTraceback } from '../../../platform/errors/errorUtils'; import { BaseError } from '../../../platform/errors/types'; -import { - traceInfo, - traceError, - traceVerbose, - traceWarning, - traceInfoIfCI, - ignoreLogging -} from '../../../platform/logging'; +import { logger, ignoreLogging } from '../../../platform/logging'; import { IFileSystemNode } from '../../../platform/common/platform/types.node'; import { IProcessServiceFactory, ObservableExecutionResult } from '../../../platform/common/process/types.node'; import { @@ -145,7 +138,7 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces this._process && !this.interrupter ) { - traceInfo('Interrupting kernel via SIGINT'); + logger.info('Interrupting kernel via SIGINT'); if (this._process.pid) { kill(this._process.pid, 'SIGINT'); } @@ -155,10 +148,10 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces this.interrupter && isPythonKernelConnection(this._kernelConnectionMetadata) ) { - traceInfo('Interrupting kernel via custom event (Win32)'); + logger.info('Interrupting kernel via custom event (Win32)'); return this.interrupter.interrupt(); } else { - traceError('No process to interrupt in KernleProcess.ts'); + logger.error('No process to interrupt in KernleProcess.ts'); } } @@ -181,7 +174,7 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces if (cancelToken.isCancellationRequested) { throw new CancellationError(); } - traceVerbose(`Kernel process ${proc?.pid}.`); + logger.debug(`Kernel process ${proc?.pid}.`); let stderr = ''; let providedExitCode: number | null; const deferred = createDeferred(); @@ -192,10 +185,10 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces proc.on('exit', (exitCode) => { exitCode = exitCode || providedExitCode; if (this.isDisposed) { - traceVerbose(`KernelProcess Exited ${pid}, Exit Code - ${exitCode}`); + logger.debug(`KernelProcess Exited ${pid}, Exit Code - ${exitCode}`); return; } - traceVerbose(`KernelProcess Exited ${pid}, Exit Code - ${exitCode}`, stderr); + logger.debug(`KernelProcess Exited ${pid}, Exit Code - ${exitCode}`, stderr); if (!this.exitEventFired) { this.exitEvent.fire({ exitCode: exitCode || undefined, @@ -205,7 +198,7 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces this.exitEventFired = true; } if (!cancelToken.isCancellationRequested) { - traceInfoIfCI(`KernelProcessExitedError raised`, stderr); + logger.ci(`KernelProcessExitedError raised`, stderr); deferred.reject( new KernelProcessExitedError(exitCode || -1, stderr, this.kernelConnectionMetadata) ); @@ -225,7 +218,7 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces sawKernelConnectionFile = true; } - traceVerbose(`Kernel output ${pid}: ${output}`); + logger.debug(`Kernel output ${pid}: ${output}`); this.sendToOutput(output); }); @@ -244,7 +237,7 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces !output.includes('to python to disable frozen modules') && !output.includes('Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION') ) { - traceVerbose(`KernelProcess error ${pid}: ${output}`); + logger.debug(`KernelProcess error ${pid}: ${output}`); this.sendToOutput(output); } }); @@ -252,10 +245,10 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces exeObs.out.done.catch((error) => { if (this.isDisposed) { - traceWarning('Kernel died', error, stderr); + logger.warn('Kernel died', error, stderr); return; } - traceError('Kernel died', error, stderr); + logger.error('Kernel died', error, stderr); deferred.reject(error); }); @@ -293,7 +286,7 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces // Do not throw an error, ignore this. // In the case of VPNs the port does not seem to get used. // Possible we're blocking it. - traceWarning(`Waited ${stopwatch.elapsedTime}ms for kernel to start`, ex); + logger.warn(`Waited ${stopwatch.elapsedTime}ms for kernel to start`, ex); // For the new experiment, we don't want to throw an error if the kernel doesn't start. if (!doNotWaitForZmqPortsToGetUsed) { @@ -305,11 +298,11 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces } catch (e) { const stdErrToLog = (stderr || '').trim(); if (!cancelToken?.isCancellationRequested && !isCancellationError(e)) { - traceError('Disposing kernel process due to an error', e); + logger.error('Disposing kernel process due to an error', e); if (e && e instanceof Error && stdErrToLog.length && e.message.includes(stdErrToLog)) { // No need to log the stderr as it's already part of the error message. } else { - traceError(stdErrToLog); + logger.error(stdErrToLog); } } // Make sure to dispose if we never connect. @@ -320,11 +313,11 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces } else { // Possible this isn't an error we recognize, hence wrap it in a user friendly message. if (cancelToken?.isCancellationRequested) { - traceVerbose('User cancelled the kernel launch'); + logger.debug('User cancelled the kernel launch'); } // If we have the python error message in std outputs, display that. const errorMessage = getErrorMessageFromPythonTraceback(stdErrToLog) || stdErrToLog.substring(0, 100); - traceInfoIfCI(`KernelDiedError raised`, errorMessage, stderr + '\n' + stderr + '\n'); + logger.ci(`KernelDiedError raised`, errorMessage, stderr + '\n' + stderr + '\n'); throw new KernelDiedError( DataScience.kernelDied(errorMessage), // Include what ever we have as the stderr. @@ -347,7 +340,7 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces return; } const pid = this._process?.pid; - traceVerbose(`Dispose Kernel process ${pid}.`); + logger.debug(`Dispose Kernel process ${pid}.`); this._disposingPromise = (async () => { await raceTimeout( 1_000, // Wait for a max of 1s, we don't want to delay killing the kernel process. @@ -360,18 +353,18 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces this.exitEvent.fire({ stderr: '' }); } } catch (ex) { - traceError(`Error disposing kernel process ${pid}`, ex); + logger.error(`Error disposing kernel process ${pid}`, ex); } swallowExceptions(async () => { if (this.connectionFile) { await this.fileSystem .delete(this.connectionFile) .catch((ex) => - traceWarning(`Failed to delete connection file ${this.connectionFile} for pid ${pid}`, ex) + logger.warn(`Failed to delete connection file ${this.connectionFile} for pid ${pid}`, ex) ); } }); - traceVerbose(`Disposed Kernel process ${pid}.`); + logger.debug(`Disposed Kernel process ${pid}.`); })(); super.dispose(); } @@ -392,7 +385,7 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces await new Promise((resolve) => { pidtree(pid, (ex: unknown, pids: number[]) => { if (ex) { - traceWarning(`Failed to kill children for ${pid}`, ex); + logger.warn(`Failed to kill children for ${pid}`, ex); } else { pids.forEach((procId) => ProcessService.kill(procId)); } @@ -401,7 +394,7 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces }); } } catch (ex) { - traceWarning(`Failed to kill children for ${pid}`, ex); + logger.warn(`Failed to kill children for ${pid}`, ex); } } @@ -422,7 +415,7 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces throw new Error('KernelSpec cannot be empty in KernelProcess.ts'); } if (!Array.isArray(kernelSpec.argv)) { - traceError('KernelSpec.argv in KernelProcess is undefined'); + logger.error('KernelSpec.argv in KernelProcess is undefined'); // eslint-disable-next-line @typescript-eslint/no-explicit-any this._launchKernelSpec = undefined; } else { @@ -534,7 +527,7 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces private async launchAsObservable(workingDirectory: string, @ignoreLogging() cancelToken: CancellationToken) { let exeObs: ObservableExecutionResult; - traceVerbose( + logger.debug( `Launching kernel ${this.kernelConnectionMetadata.id} for ${getDisplayPath( this.resource )} in ${getDisplayPath(workingDirectory)} with ports ${this.connection.control_port}, ${ @@ -584,11 +577,11 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces // See the code ProcessPollingWindows inside of ipykernel for it listening to this event handle. env.JPY_INTERRUPT_EVENT = `${handle}`; - traceInfoIfCI( + logger.ci( `Got interrupt handle kernel id ${handle} for interpreter ${this._kernelConnectionMetadata.interpreter.id}` ); } catch (ex) { - traceError( + logger.error( `Failed to get interrupt handle kernel id ${this._kernelConnectionMetadata.id} for interpreter ${this._kernelConnectionMetadata.interpreter.id}`, ex ); @@ -610,7 +603,7 @@ export class KernelProcess extends ObservableDisposable implements IKernelProces // If we are not python just use the ProcessExecutionFactory // First part of argument is always the executable. const executable = this.launchKernelSpec.argv[0]; - traceInfo(`Launching Raw Kernel ${this.launchKernelSpec.display_name} # ${executable}`); + logger.info(`Launching Raw Kernel ${this.launchKernelSpec.display_name} # ${executable}`); const [executionService, env] = await Promise.all([ this.processExecutionFactory.create(this.resource, cancelToken), // If we have an interpreter always use that, its possible we are launching a kernel that is associated with a Python environment diff --git a/src/kernels/raw/launcher/kernelProcess.node.unit.test.ts b/src/kernels/raw/launcher/kernelProcess.node.unit.test.ts index 051910395de..0b00daa908f 100644 --- a/src/kernels/raw/launcher/kernelProcess.node.unit.test.ts +++ b/src/kernels/raw/launcher/kernelProcess.node.unit.test.ts @@ -38,7 +38,7 @@ import { JupyterPaths } from '../finder/jupyterPaths.node'; import { waitForCondition } from '../../../test/common.node'; import { uriEquals } from '../../../test/datascience/helpers'; import { IS_REMOTE_NATIVE_TEST } from '../../../test/constants'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IPlatformService } from '../../../platform/common/platform/types'; import { IPythonExecutionFactory, IPythonExecutionService } from '../../../platform/interpreter/types.node'; import { createObservable } from '../../../platform/common/process/proc.node'; @@ -456,12 +456,12 @@ suite('Kernel Process', () => { }); // setup(async function () { - // traceInfo(`Start Test ${this.currentTest?.title}`); + // logger.info(`Start Test ${this.currentTest?.title}`); // }); teardown(function () { rewiremock.disable(); sinon.restore(); - traceInfo(`End Test Complete ${this.currentTest?.title}`); + logger.info(`End Test Complete ${this.currentTest?.title}`); disposables = dispose(disposables); }); diff --git a/src/kernels/raw/session/rawJupyterSession.node.ts b/src/kernels/raw/session/rawJupyterSession.node.ts index b1944d7c68e..2fb2f368716 100644 --- a/src/kernels/raw/session/rawJupyterSession.node.ts +++ b/src/kernels/raw/session/rawJupyterSession.node.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import type { KernelMessage } from '@jupyterlab/services'; -import { traceVerbose, traceInfoIfCI } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { Resource } from '../../../platform/common/types'; import { raceTimeout } from '../../../platform/common/utils/async'; import { IRawKernelSession, LocalKernelConnectionMetadata } from '../../types'; @@ -38,7 +38,7 @@ export class RawJupyterSessionWrapper if (this.session.kernel) { return this.session.kernel.status; } - traceInfoIfCI(`Real kernel is ${this.session.kernel ? 'defined' : 'undefined'}`); + logger.ci(`Real kernel is ${this.session.kernel ? 'defined' : 'undefined'}`); return 'unknown'; } @@ -64,7 +64,7 @@ export class RawJupyterSessionWrapper try { await waitForIdleOnSession(this.kernelConnectionMetadata, this.resource, this.session, timeout, token); } catch (ex) { - traceInfoIfCI(`Error waiting for idle`, ex); + logger.ci(`Error waiting for idle`, ex); await this.shutdown().catch(noop); throw ex; } @@ -78,11 +78,11 @@ export class RawJupyterSessionWrapper this.terminatingStatus = 'terminating'; this.statusChanged.emit('terminating'); const kernelIdForLogging = `${this.session.kernel?.id}, ${this.kernelConnectionMetadata?.id}`; - traceVerbose(`Shutdown session ${kernelIdForLogging} - start called from ${new Error('').stack}`); + logger.debug(`Shutdown session ${kernelIdForLogging} - start called from ${new Error('').stack}`); suppressShutdownErrors(this.session.kernel); await raceTimeout(1000, this.session.shutdown().catch(noop)); this.didShutdown.fire(); super.dispose(); - traceVerbose(`Shutdown session ${kernelIdForLogging} - shutdown complete`); + logger.debug(`Shutdown session ${kernelIdForLogging} - shutdown complete`); } } diff --git a/src/kernels/raw/session/rawKernelConnection.node.ts b/src/kernels/raw/session/rawKernelConnection.node.ts index e03a485f197..d471e0d8670 100644 --- a/src/kernels/raw/session/rawKernelConnection.node.ts +++ b/src/kernels/raw/session/rawKernelConnection.node.ts @@ -4,7 +4,7 @@ import type { Kernel, KernelSpec, KernelMessage, ServerConnection } from '@jupyterlab/services'; /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */ import uuid from 'uuid/v4'; -import { traceError, traceInfo, traceVerbose, traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IDisposable, Resource } from '../../../platform/common/types'; import { noop, swallowExceptions } from '../../../platform/common/utils/misc'; import { @@ -208,7 +208,7 @@ export class RawKernelConnection implements Kernel.IKernelConnection { this.kernelProcess?.dispose().catch(noop), this.realKernel ?.shutdown() - .catch((ex) => traceWarning(`Failed to shutdown kernel, ${this.kernelConnectionMetadata.id}`, ex)) + .catch((ex) => logger.warn(`Failed to shutdown kernel, ${this.kernelConnectionMetadata.id}`, ex)) ]); if (kernelExitedError) { throw kernelExitedError; @@ -222,9 +222,9 @@ export class RawKernelConnection implements Kernel.IKernelConnection { throw new KernelConnectionTimeoutError(this.kernelConnectionMetadata); } if (isCancellationError(error) || token.isCancellationRequested) { - traceVerbose('Starting of raw session cancelled by user'); + logger.debug('Starting of raw session cancelled by user'); } else { - traceError(`Failed to connect raw kernel session: ${error}`); + logger.error(`Failed to connect raw kernel session: ${error}`); } throw error; } finally { @@ -247,7 +247,7 @@ export class RawKernelConnection implements Kernel.IKernelConnection { return; } - traceError(`Disposing session as kernel process died ExitCode: ${e.exitCode}, Reason: ${e.reason}`); + logger.error(`Disposing session as kernel process died ExitCode: ${e.exitCode}, Reason: ${e.reason}`); // Send telemetry so we know why the kernel process exited, // as this affects our kernel startup success sendKernelTelemetryEvent( @@ -315,7 +315,7 @@ export class RawKernelConnection implements Kernel.IKernelConnection { resources }; } - traceError('Fetching kernel spec from raw kernel using JLab API'); + logger.error('Fetching kernel spec from raw kernel using JLab API'); return this.realKernel!.spec; } public sendShellMessage( @@ -349,7 +349,7 @@ export class RawKernelConnection implements Kernel.IKernelConnection { if (this.kernelProcess?.canInterrupt) { return this.kernelProcess?.interrupt(); } else if (this.kernelConnectionMetadata.kernelSpec.interrupt_mode === 'message') { - traceInfo(`Interrupting kernel with a shell message`); + logger.info(`Interrupting kernel with a shell message`); const jupyterLab = require('@jupyterlab/services') as typeof import('@jupyterlab/services'); const msg = jupyterLab.KernelMessage.createMessage({ msgType: 'interrupt_request' as any, @@ -359,10 +359,10 @@ export class RawKernelConnection implements Kernel.IKernelConnection { content: {} }) as any as KernelMessage.IShellMessage<'inspect_request'>; await this.realKernel!.sendShellMessage<'interrupt_request'>(msg as any, true, true).done.catch((ex) => - traceError('Failed to interrupt via a message', ex) + logger.error('Failed to interrupt via a message', ex) ); } else { - traceError('Kernel interrupt not supported'); + logger.error('Kernel interrupt not supported'); } } public requestKernelInfo() { @@ -483,11 +483,11 @@ async function postStartKernel( ): Promise { try { // Wait for it to be ready - traceVerbose('Waiting for Raw Session to be ready in postStartRawSession'); + logger.debug('Waiting for Raw Session to be ready in postStartRawSession'); await raceCancellationError(token, waitForReady(kernel, kernelConnectionMetadata, launchTimeout)); - traceVerbose('Successfully waited for Raw Session to be ready in postStartRawSession'); + logger.debug('Successfully waited for Raw Session to be ready in postStartRawSession'); } catch (ex) { - traceError('Failed waiting for Raw Session to be ready', ex); + logger.error('Failed waiting for Raw Session to be ready', ex); if (isCancellationError(ex) || token.isCancellationRequested) { throw new CancellationError(); } @@ -496,7 +496,7 @@ async function postStartKernel( // Attempt to get kernel to respond to requests (this is what jupyter does today). // Kinda warms up the kernel communication & ensure things are in the right state. - traceVerbose(`Kernel status is '${kernel?.status}' before requesting kernel info and after ready`); + logger.debug(`Kernel status is '${kernel?.status}' before requesting kernel info and after ready`); // Lets wait for the response (max of 3s), like jupyter (python code) & jupyter client (jupyter lab npm) does. // Lets not wait for full timeout, we don't want to slow kernel startup. // Note: in node_modules/@jupyterlab/services/lib/kernel/default.js we only wait for 3s. @@ -540,7 +540,7 @@ async function postStartKernel( while (stopWatch.elapsedTime < launchTimeout * 1000) { attempts += 1; try { - traceVerbose('Sending request for kernelInfo'); + logger.debug('Sending request for kernelInfo'); // In jupyter_server/services/kernels/connection/channels.py, // the request for kernel information is sent on both channels // To ensure max compatibility, we'll do the same. @@ -553,24 +553,24 @@ async function postStartKernel( sleep(Math.min(launchTimeout, 500)).then(noop) ); } catch (ex) { - traceError('Failed to request kernel info', ex); + logger.error('Failed to request kernel info', ex); throw ex; } if (gotIoPubMessage.completed && kernelInfoRequestHandled.completed) { - traceVerbose(`Got response for requestKernelInfo`); + logger.debug(`Got response for requestKernelInfo`); break; } else { - traceVerbose(`Did not get a response for requestKernelInfo`); + logger.debug(`Did not get a response for requestKernelInfo`); continue; } } if (gotIoPubMessage.completed && kernelInfoRequestHandled.completed) { - traceVerbose( + logger.debug( `Successfully completed postStartRawSession after ${attempts} attempt(s) in ${stopWatch.elapsedTime}ms` ); } else { - traceWarning( + logger.warn( `Didn't get response for requestKernelInfo after ${attempts} attempt(s) in ${stopWatch.elapsedTime}ms.` ); } @@ -659,7 +659,7 @@ function newRawKernel(kernelProcess: IKernelProcess, clientId: string, username: }); if (workspace.getConfiguration('jupyter').get('enablePythonKernelLogging', false)) { realKernel.anyMessage.connect((_, msg) => { - traceVerbose(`[AnyMessage Event] [${msg.direction}] [${kernelProcess.pid}] ${JSON.stringify(msg.msg)}`); + logger.debug(`[AnyMessage Event] [${msg.direction}] [${kernelProcess.pid}] ${JSON.stringify(msg.msg)}`); }); } @@ -677,27 +677,27 @@ async function waitForReady( kernelConnectionMetadata: LocalKernelConnectionMetadata, launchTimeout: number ): Promise { - traceVerbose(`Waiting for Raw session to be ready, status: ${kernel.connectionStatus}`); + logger.debug(`Waiting for Raw session to be ready, status: ${kernel.connectionStatus}`); // When our kernel connects and gets a status message it triggers the ready promise const deferred = createDeferred<'connected'>(); const handler = (_: unknown, status: Kernel.ConnectionStatus) => { if (status == 'connected') { - traceVerbose('Raw session connected'); + logger.debug('Raw session connected'); deferred.resolve(status); } else { - traceVerbose(`Raw session not connected, status: ${status}`); + logger.debug(`Raw session not connected, status: ${status}`); } }; kernel.connectionStatusChanged.connect(handler); if (kernel.connectionStatus === 'connected') { - traceVerbose('Raw session connected'); + logger.debug('Raw session connected'); deferred.resolve(kernel.connectionStatus); } - traceVerbose('Waiting for Raw session to be ready'); + logger.debug('Waiting for Raw session to be ready'); const result = await raceTimeout(launchTimeout, deferred.promise); kernel.connectionStatusChanged.disconnect(handler); - traceVerbose(`Waited for Raw session to be ready & got status: ${result}`); + logger.debug(`Waited for Raw session to be ready & got status: ${result}`); if (result !== 'connected') { throw new KernelConnectionTimeoutError(kernelConnectionMetadata); diff --git a/src/kernels/raw/session/rawKernelSessionFactory.node.ts b/src/kernels/raw/session/rawKernelSessionFactory.node.ts index bf09511d6f1..27aeef725b6 100644 --- a/src/kernels/raw/session/rawKernelSessionFactory.node.ts +++ b/src/kernels/raw/session/rawKernelSessionFactory.node.ts @@ -5,7 +5,7 @@ import * as vscode from 'vscode'; import * as path from '../../../platform/vscode-path/path'; import { untildify } from '../../../platform/common/platform/fileUtils.node'; import { injectable, inject } from 'inversify'; -import { traceVerbose, traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { getDisplayPath, getFilePath } from '../../../platform/common/platform/fs-paths'; import { IConfigurationService, type Resource } from '../../../platform/common/types'; import { trackKernelResourceInformation } from '../../telemetry/helper'; @@ -34,7 +34,7 @@ export class RawKernelSessionFactory implements IRawKernelSessionFactory { ) {} public async create(options: LocaLKernelSessionCreationOptions): Promise { - traceVerbose(`Creating raw notebook for resource '${getDisplayPath(options.resource)}'`); + logger.debug(`Creating raw notebook for resource '${getDisplayPath(options.resource)}'`); let session: RawSessionConnection | undefined; const cwdTracker = getNotebookTelemetryTracker(options.resource)?.computeCwd(); const [workingDirectory, localWorkingDirectory] = await Promise.all([ @@ -69,14 +69,14 @@ export class RawKernelSessionFactory implements IRawKernelSessionFactory { await raceCancellationError(options.token, session.startKernel(options)); } catch (error) { if (isCancellationError(error) || options.token.isCancellationRequested) { - traceVerbose('Starting of raw session cancelled by user'); + logger.debug('Starting of raw session cancelled by user'); } else { - traceError(`Failed to connect raw kernel session: ${error}`); + logger.error(`Failed to connect raw kernel session: ${error}`); } // Make sure we shut down our session in case we started a process session ?.shutdown() - .catch((error) => traceError(`Failed to dispose of raw session on launch error: ${error} `)) + .catch((error) => logger.error(`Failed to dispose of raw session on launch error: ${error} `)) .finally(() => session?.dispose()) .catch(noop); throw error; diff --git a/src/kernels/raw/session/rawSessionConnection.node.ts b/src/kernels/raw/session/rawSessionConnection.node.ts index 37762a32177..b1741d8c128 100644 --- a/src/kernels/raw/session/rawSessionConnection.node.ts +++ b/src/kernels/raw/session/rawSessionConnection.node.ts @@ -4,7 +4,7 @@ import type { Kernel, KernelMessage, ServerConnection, Session } from '@jupyterlab/services'; import { Signal } from '@lumino/signaling'; import uuid from 'uuid/v4'; -import { traceInfoIfCI, traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { Resource } from '../../../platform/common/types'; import { Telemetry } from '../../../telemetry'; import { LocalKernelConnectionMetadata } from '../../types'; @@ -162,7 +162,7 @@ export class RawSessionConnection implements Session.ISessionConnection { this.statusChanged.emit('terminating'); await this._kernel .shutdown() - .catch((ex) => traceWarning(`Failed to shutdown kernel, ${this.kernelConnectionMetadata.id}`, ex)); + .catch((ex) => logger.warn(`Failed to shutdown kernel, ${this.kernelConnectionMetadata.id}`, ex)); this.isTerminating = false; // Before triggering any status events ensure this is marked as disposed. if (this._isDisposing) { @@ -172,7 +172,7 @@ export class RawSessionConnection implements Session.ISessionConnection { this.statusChanged.emit(this.status); } private onKernelStatus(_sender: Kernel.IKernelConnection, state: KernelMessage.Status) { - traceInfoIfCI(`RawSession status changed to ${state}`); + logger.ci(`RawSession status changed to ${state}`); this.statusChanged.emit(state); } diff --git a/src/kernels/raw/session/rawSocket.node.ts b/src/kernels/raw/session/rawSocket.node.ts index 61c989ca6df..d7011c484f0 100644 --- a/src/kernels/raw/session/rawSocket.node.ts +++ b/src/kernels/raw/session/rawSocket.node.ts @@ -6,7 +6,7 @@ import * as wireProtocol from '@nteract/messaging/lib/wire-protocol'; import uuid from 'uuid/v4'; import * as WebSocketWS from 'ws'; import type { Dealer, Subscriber } from 'zeromq'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { noop } from '../../../platform/common/utils/misc'; import { IWebSocketLike } from '../../common/kernelSocketWrapper'; import { IKernelSocket } from '../../types'; @@ -69,7 +69,7 @@ export class RawSocket implements IWebSocketLike, IKernelSocket, IDisposable { try { closable.close(); } catch (ex) { - traceError(`Error during socket shutdown`, ex); + logger.error(`Error during socket shutdown`, ex); } }; closer(this.channels.control); @@ -123,8 +123,8 @@ export class RawSocket implements IWebSocketLike, IKernelSocket, IDisposable { ): T { const result = ctor(); result.connect(formConnectionString(connection, channel)); - this.processSocketMessages(channel, result).catch( - traceError.bind(`Failed to read messages from channel ${channel}`) + this.processSocketMessages(channel, result).catch((ex) => + logger.error(`Failed to read messages from channel ${channel}`, ex) ); return result; } @@ -242,7 +242,7 @@ export class RawSocket implements IWebSocketLike, IKernelSocket, IDisposable { this.onmessage({ data: message as any, type: 'message', target: this }); } catch (ex) { // Swallow this error, so that other messages get processed. - traceError(`Failed to handle message in Jupyter Kernel package ${JSON.stringify(message)}`, ex); + logger.error(`Failed to handle message in Jupyter Kernel package ${JSON.stringify(message)}`, ex); } } } @@ -262,7 +262,7 @@ export class RawSocket implements IWebSocketLike, IKernelSocket, IDisposable { try { await this.postToSocket(msg.channel, data); } catch (ex) { - traceError(`Failed to write data to the kernel channel ${msg.channel}`, data, ex); + logger.error(`Failed to write data to the kernel channel ${msg.channel}`, data, ex); // No point throwing this error, as that would mean nothing else works from here on end. // Lets ignore this error but log it and then continue // Hopefully users will file bugs and we can fix this (based on the error message). @@ -282,10 +282,10 @@ export class RawSocket implements IWebSocketLike, IKernelSocket, IDisposable { const socket = (this.channels as any)[channel]; if (socket) { (socket as Dealer).send(data).catch((exc) => { - traceError(`Error communicating with the kernel`, exc); + logger.error(`Error communicating with the kernel`, exc); }); } else { - traceError(`Attempting to send message on invalid channel: ${channel}`); + logger.error(`Attempting to send message on invalid channel: ${channel}`); } } } diff --git a/src/kernels/raw/session/zeromq.node.ts b/src/kernels/raw/session/zeromq.node.ts index 1c8b2d626e7..94b71879045 100644 --- a/src/kernels/raw/session/zeromq.node.ts +++ b/src/kernels/raw/session/zeromq.node.ts @@ -4,7 +4,7 @@ import * as fs from 'fs-extra'; import * as path from '../../../platform/vscode-path/path'; import * as os from 'os'; -import { traceInfo, traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { Telemetry, sendTelemetryEvent } from '../../../telemetry'; import { noop } from '../../../platform/common/utils/misc'; import { DistroInfo, getDistroInfo } from '../../../platform/common/platform/linuxDistro.node'; @@ -20,13 +20,13 @@ export function getZeroMQ(): typeof import('zeromq') { } catch (e) { try { const zmq = require(path.join(EXTENSION_ROOT_DIR, 'dist', 'node_modules', 'zeromqold')); - traceInfo('ZMQ loaded via fallback mechanism.'); + logger.info('ZMQ loaded via fallback mechanism.'); sendZMQTelemetry(false, true, e.message || e.toString()).catch(noop); return zmq; } catch (e2) { sendZMQTelemetry(true, true, e.message || e.toString(), e2.message || e2.toString()).catch(noop); - traceWarning(`Exception while attempting zmq :`, e.message || e); // No need to display the full stack (when this fails we know why if fails, hence a stack is not useful) - traceWarning(`Exception while attempting zmq (fallback) :`, e2.message || e2); // No need to display the full stack (when this fails we know why if fails, hence a stack is not useful) + logger.warn(`Exception while attempting zmq :`, e.message || e); // No need to display the full stack (when this fails we know why if fails, hence a stack is not useful) + logger.warn(`Exception while attempting zmq (fallback) :`, e2.message || e2); // No need to display the full stack (when this fails we know why if fails, hence a stack is not useful) throw e2; } } @@ -61,7 +61,7 @@ async function getLocalZmqBinaries() { .replace(/\//g, '') ); } catch (ex) { - traceWarning(`Failed to determine local zmq binaries.`, ex); + logger.warn(`Failed to determine local zmq binaries.`, ex); return ['Failed to determine local zmq binaries.']; } } @@ -133,7 +133,7 @@ function getPlatformInfo() { zmqarch: arch }; } catch (ex) { - traceWarning(`Failed to determine platform information used to load zeromq binary.`, ex); + logger.warn(`Failed to determine platform information used to load zeromq binary.`, ex); return {}; } } diff --git a/src/kernels/telemetry/notebookTelemetry.ts b/src/kernels/telemetry/notebookTelemetry.ts index 5b998eddfa8..a81edf948e1 100644 --- a/src/kernels/telemetry/notebookTelemetry.ts +++ b/src/kernels/telemetry/notebookTelemetry.ts @@ -9,7 +9,7 @@ import { sendKernelTelemetryEvent } from './sendKernelTelemetryEvent'; import { Telemetry } from '../../platform/common/constants'; import type { Environment } from '@vscode/python-extension'; import { getCellMetadata } from '../../platform/common/utils'; -import { traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; /* eslint-disable @typescript-eslint/no-use-before-define */ @@ -516,7 +516,7 @@ function computeNotebookSummary(notebook: NotebookDocument) { } }); } catch (error) { - traceWarning(`Error parsing attachments in cell metadata`, error); + logger.warn(`Error parsing attachments in cell metadata`, error); } } else { notebookSummary.codeCellCount += 1; diff --git a/src/notebooks/controllers/commands/installPythonControllerCommands.ts b/src/notebooks/controllers/commands/installPythonControllerCommands.ts index 6376dcd935f..0ffbcc0ca6d 100644 --- a/src/notebooks/controllers/commands/installPythonControllerCommands.ts +++ b/src/notebooks/controllers/commands/installPythonControllerCommands.ts @@ -11,7 +11,7 @@ import { IDisposableRegistry } from '../../../platform/common/types'; import { raceTimeout } from '../../../platform/common/utils/async'; import { Common, DataScience } from '../../../platform/common/utils/localize'; import { noop } from '../../../platform/common/utils/misc'; -import { traceError, traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { ProgressReporter } from '../../../platform/progress/progressReporter'; import { sendTelemetryEvent } from '../../../telemetry'; @@ -93,14 +93,14 @@ export class InstallPythonControllerCommands implements IExtensionSyncActivation // Make sure that we didn't timeout waiting for the hook if (this.extensionChecker.isPythonExtensionInstalled && hookResult === hooked) { - traceVerbose('Python Extension installed via Kernel Picker command'); + logger.debug('Python Extension installed via Kernel Picker command'); sendTelemetryEvent(Telemetry.PythonExtensionInstalledViaKernelPicker, undefined, { action: 'success' }); return true; } else { - traceError('Failed to install Python Extension via Kernel Picker command'); + logger.error('Failed to install Python Extension via Kernel Picker command'); sendTelemetryEvent(Telemetry.PythonExtensionInstalledViaKernelPicker, undefined, { action: 'failed' }); diff --git a/src/notebooks/controllers/controllerRegistration.ts b/src/notebooks/controllers/controllerRegistration.ts index a0a50b80882..d51b7fcf617 100644 --- a/src/notebooks/controllers/controllerRegistration.ts +++ b/src/notebooks/controllers/controllerRegistration.ts @@ -18,7 +18,7 @@ import { } from '../../platform/common/types'; import { noop } from '../../platform/common/utils/misc'; import { IServiceContainer } from '../../platform/ioc/types'; -import { traceError, traceInfoIfCI, traceVerbose, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { NotebookCellLanguageService } from '../languages/cellLanguageService'; import { sendKernelListTelemetry } from '../telemetry/kernelTelemetry'; import { PythonEnvironmentFilter } from '../../platform/interpreter/filter/filterService'; @@ -108,7 +108,7 @@ export class ControllerRegistration implements IControllerRegistration, IExtensi this.canControllerBeDisposed(controller) ) { // This item was selected but is no longer allowed in the kernel list. Remove it - traceWarning( + logger.warn( `Removing controller ${controller.id} for ${controller.connection.kind} from kernel list` ); controller.dispose(); @@ -133,7 +133,7 @@ export class ControllerRegistration implements IControllerRegistration, IExtensi this.controllersPromise = this.loadControllersImpl(); sendKernelListTelemetry(this.registered.map((v) => v.connection)); - traceInfoIfCI(`Providing notebook controllers with length ${this.registered.length}.`); + logger.ci(`Providing notebook controllers with length ${this.registered.length}.`); } public get loaded() { return this.controllersPromise; @@ -174,7 +174,7 @@ export class ControllerRegistration implements IControllerRegistration, IExtensi return false; } if (!connectionIsStillValid) { - traceVerbose( + logger.debug( `Controller ${controller.connection.kind}:'${controller.id}' for view = '${controller.viewType}' is no longer a valid` ); } @@ -182,7 +182,7 @@ export class ControllerRegistration implements IControllerRegistration, IExtensi }); // If we have any out of date connections, dispose of them disposedControllers.forEach((controller) => { - traceWarning( + logger.warn( `Disposing old controller ${controller.connection.kind}:'${controller.id}' for view = '${controller.viewType}'` ); controller.dispose(); // This should remove it from the registered list @@ -210,7 +210,7 @@ export class ControllerRegistration implements IControllerRegistration, IExtensi this.registered .filter((item) => deletedConnections.has(item.connection.id)) .forEach((controller) => { - traceWarning( + logger.warn( `Deleting controller ${controller.id} as it is associated with a connection that has been deleted ${controller.connection.kind}:${controller.id}` ); controller.dispose(); @@ -240,7 +240,7 @@ export class ControllerRegistration implements IControllerRegistration, IExtensi c.connection.serverProviderHandle.id === item.id && c.connection.serverProviderHandle.handle === item.handle ) { - traceWarning( + logger.warn( `Deleting controller ${c.id} as it is associated with a connection that has been removed` ); c.dispose(); @@ -266,7 +266,7 @@ export class ControllerRegistration implements IControllerRegistration, IExtensi // If we have a notebook opened and its using a kernel. // Else we end up killing the execution as well. if (this.isFiltered(item.connection) && this.canControllerBeDisposed(item)) { - traceWarning( + logger.warn( `Deleting controller ${item.id} as it is associated with a connection that has been hidden` ); item.dispose(); @@ -311,7 +311,7 @@ export class ControllerRegistration implements IControllerRegistration, IExtensi ): { added: IVSCodeNotebookController[]; existing: IVSCodeNotebookController[] } { const added: IVSCodeNotebookController[] = []; const existing: IVSCodeNotebookController[] = []; - traceInfoIfCI(`Create Controller for ${metadata.kind} and id '${metadata.id}' for view ${types.join(', ')}`); + logger.ci(`Create Controller for ${metadata.kind} and id '${metadata.id}' for view ${types.join(', ')}`); try { // Create notebook selector types @@ -335,16 +335,16 @@ export class ControllerRegistration implements IControllerRegistration, IExtensi // Add to results so that callers can find existing.push(controller); - traceInfoIfCI( + logger.ci( `Found existing controller '${controller.id}', not creating a new one just updating it` ); return false; } else if (this.isFiltered(metadata)) { // Filter out those in our kernel filter - traceInfoIfCI(`Existing controller '${id}' will be excluded as it is filtered`); + logger.ci(`Existing controller '${id}' will be excluded as it is filtered`); return false; } - traceInfoIfCI(`Existing controller not found for '${id}', hence creating a new one`); + logger.ci(`Existing controller not found for '${id}', hence creating a new one`); return true; }) .forEach(([id, viewType]) => { @@ -366,7 +366,7 @@ export class ControllerRegistration implements IControllerRegistration, IExtensi const controllerDisposables: IDisposable[] = []; controller.onDidDispose( () => { - traceInfoIfCI( + logger.ci( `Deleting controller '${controller.id}' associated with view ${viewType} from registration as it was disposed` ); this.registeredControllers.delete(controller.id); @@ -384,7 +384,7 @@ export class ControllerRegistration implements IControllerRegistration, IExtensi added.push(controller); controller.onNotebookControllerSelected( (e) => { - traceInfoIfCI(`Controller ${e.controller?.id} selected for ${e.notebook.uri.toString()}`); + logger.ci(`Controller ${e.controller?.id} selected for ${e.notebook.uri.toString()}`); this.selectedControllers.set(e.notebook, e.controller); // Now notify out that we have updated a notebooks controller this.selectedEmitter.fire(e); @@ -407,7 +407,7 @@ export class ControllerRegistration implements IControllerRegistration, IExtensi // Hence swallow cancellation errors. return { added, existing }; } - traceError(`Failed to create notebook controller for ${metadata.id}`, ex); + logger.error(`Failed to create notebook controller for ${metadata.id}`, ex); } return { added, existing }; } diff --git a/src/notebooks/controllers/ipywidgets/message/commonMessageCoordinator.ts b/src/notebooks/controllers/ipywidgets/message/commonMessageCoordinator.ts index 27eb6268f56..4999fec80d5 100644 --- a/src/notebooks/controllers/ipywidgets/message/commonMessageCoordinator.ts +++ b/src/notebooks/controllers/ipywidgets/message/commonMessageCoordinator.ts @@ -4,7 +4,7 @@ import type { KernelMessage } from '@jupyterlab/services'; import { Event, EventEmitter, NotebookDocument, Uri, commands, env, window } from 'vscode'; import { STANDARD_OUTPUT_CHANNEL, WIDGET_VERSION_NON_PYTHON_KERNELS } from '../../../../platform/common/constants'; -import { traceTrace, traceError, traceInfoIfCI } from '../../../../platform/logging'; +import { logger } from '../../../../platform/logging'; import { IDisposableRegistry, IOutputChannel, @@ -92,7 +92,7 @@ export class CommonMessageCoordinator { // Attach message requests to this webview (should dupe to all of them) this.postMessage( (e) => { - traceInfoIfCI(`${ConsoleForegroundColors.Green}Widget Coordinator sent ${e.message}`); + logger.ci(`${ConsoleForegroundColors.Green}Widget Coordinator sent ${e.message}`); // Special case for webview URI translation if (e.message === InteractiveWindowMessages.ConvertUriForUseInWebViewRequest) { this.onMessage(webview, InteractiveWindowMessages.ConvertUriForUseInWebViewResponse, { @@ -167,7 +167,7 @@ export class CommonMessageCoordinator { } // IPyWidgets scripts will not be loaded if we're unable to determine the version of IPyWidgets. const version = await deferred.promise; - traceTrace(`Version of IPyWidgets ${version} determined after ${stopWatch.elapsedTime / 1000}s`); + logger.trace(`Version of IPyWidgets ${version} determined after ${stopWatch.elapsedTime / 1000}s`); webview .postMessage({ type: IPyWidgetMessages.IPyWidgets_Reply_Widget_Version, @@ -177,7 +177,7 @@ export class CommonMessageCoordinator { }; webview.onDidReceiveMessage( async (m) => { - traceInfoIfCI(`${ConsoleForegroundColors.Green}Widget Coordinator received ${m.type}`); + logger.ci(`${ConsoleForegroundColors.Green}Widget Coordinator received ${m.type}`); this.onMessage(webview, m.type, m.payload); if (m.type === IPyWidgetMessages.IPyWidgets_Request_Widget_Version) { await sendIPyWidgetsVersion(); @@ -189,7 +189,7 @@ export class CommonMessageCoordinator { void env.openExternal(Uri.parse(m.url)); } if (m.type === IPyWidgetMessages.IPyWidgets_Ready) { - traceTrace('Web view is ready to receive widget messages'); + logger.trace('Web view is ready to receive widget messages'); this.readyMessageReceived = true; this.sendPendingWebViewMessages(webview); } @@ -280,7 +280,7 @@ export class CommonMessageCoordinator { } }, noop); } - traceError(`Widget load failure ${errorMessage}`, widgetScriptSources, payload); + logger.error(`Widget load failure ${errorMessage}`, widgetScriptSources, payload); sendTelemetryEvent(Telemetry.IPyWidgetLoadFailure, 0, { isOnline: payload.isOnline, @@ -311,7 +311,7 @@ export class CommonMessageCoordinator { } private sendRenderFailureTelemetry(payload: Error) { try { - traceError('Error rendering a widget: ', payload); + logger.error('Error rendering a widget: ', payload); sendTelemetryEvent(Telemetry.IPyWidgetRenderFailure); } catch { // Do nothing on a failure @@ -327,7 +327,7 @@ export class CommonMessageCoordinator { const errorMsg = msg as KernelMessage.IErrorMsg; errorMsg.content.traceback = errorMsg.content.traceback.map(stripAnsi); } - traceTrace(`Unhandled widget kernel message: ${msg.header.msg_type} ${msg.content}`); + logger.trace(`Unhandled widget kernel message: ${msg.header.msg_type} ${msg.content}`); this.jupyterOutput.appendLine( DataScience.unhandledMessage(msg.header.msg_type, JSON.stringify(msg.content)) ); @@ -366,7 +366,7 @@ export class CommonMessageCoordinator { // If no one is listening to the messages, then cache these. // It means its too early to dispatch the messages, we need to wait for the event handlers to get bound. if (!this.listeningToPostMessageEvent) { - traceInfoIfCI(`${ConsoleForegroundColors.Green}Queuing messages (no listeners)`); + logger.ci(`${ConsoleForegroundColors.Green}Queuing messages (no listeners)`); this.cachedMessages.push(data); return; } diff --git a/src/notebooks/controllers/ipywidgets/message/ipyWidgetMessageDispatcher.ts b/src/notebooks/controllers/ipywidgets/message/ipyWidgetMessageDispatcher.ts index e53f14ad3aa..9aa328c71e7 100644 --- a/src/notebooks/controllers/ipywidgets/message/ipyWidgetMessageDispatcher.ts +++ b/src/notebooks/controllers/ipywidgets/message/ipyWidgetMessageDispatcher.ts @@ -5,7 +5,7 @@ import type { Kernel, KernelMessage } from '@jupyterlab/services'; import uuid from 'uuid/v4'; import { Event, EventEmitter, NotebookDocument } from 'vscode'; import type { Data as WebSocketData } from 'ws'; -import { traceTrace, traceError } from '../../../../platform/logging'; +import { logger } from '../../../../platform/logging'; import { Identifiers, WIDGET_MIMETYPE } from '../../../../platform/common/constants'; import { IDisposable } from '../../../../platform/common/types'; import { Deferred, createDeferred } from '../../../../platform/common/utils/async'; @@ -119,9 +119,9 @@ export class IPyWidgetMessageDispatcher implements IIPyWidgetMessageDispatcher { case IPyWidgetMessages.IPyWidgets_logMessage: { const payload: IInteractiveWindowMapping[IPyWidgetMessages.IPyWidgets_logMessage] = message.payload; if (payload.category === 'error') { - traceError(`Widget Error: ${payload.message}`); + logger.error(`Widget Error: ${payload.message}`); } else { - traceTrace(`Widget Message: ${payload.message}`); + logger.trace(`Widget Message: ${payload.message}`); } break; } @@ -419,7 +419,7 @@ export class IPyWidgetMessageDispatcher implements IIPyWidgetMessageDispatcher { // & not the widget (renderer/webview side) kernel this.pendingMessages.shift(); } catch (ex) { - traceError('Failed to send message to Kernel', ex); + logger.error('Failed to send message to Kernel', ex); return; } } @@ -437,7 +437,7 @@ export class IPyWidgetMessageDispatcher implements IIPyWidgetMessageDispatcher { return; } - traceTrace(`Registering commtarget ${targetName}`); + logger.trace(`Registering commtarget ${targetName}`); this.commTargetsRegistered.add(targetName); this.pendingTargetNames.delete(targetName); diff --git a/src/notebooks/controllers/ipywidgets/scriptSourceProvider/baseIPyWidgetScriptManager.ts b/src/notebooks/controllers/ipywidgets/scriptSourceProvider/baseIPyWidgetScriptManager.ts index 5bff4202edc..56f1fe9521b 100644 --- a/src/notebooks/controllers/ipywidgets/scriptSourceProvider/baseIPyWidgetScriptManager.ts +++ b/src/notebooks/controllers/ipywidgets/scriptSourceProvider/baseIPyWidgetScriptManager.ts @@ -5,7 +5,7 @@ import { Uri } from 'vscode'; import { splitLines, trimQuotes } from '../../../../platform/common/helpers'; import { getDisplayPath } from '../../../../platform/common/platform/fs-paths'; import { IDisposable } from '../../../../platform/common/types'; -import { traceError, traceWarning } from '../../../../platform/logging'; +import { logger } from '../../../../platform/logging'; import { sendTelemetryEvent, Telemetry } from '../../../../telemetry'; import { IKernel, isLocalConnection } from '../../../../kernels/types'; import { getTelemetrySafeHashedString } from '../../../../platform/telemetry/helpers'; @@ -183,11 +183,11 @@ export abstract class BaseIPyWidgetScriptManager implements IIPyWidgetScriptMana if (isCI) { message += `with contents ${contents}`; } - traceWarning(message); + logger.warn(message); } return config; } catch (ex) { - traceError( + logger.error( `Failed to extract require.config entry for ${widgetFolderName} from ${getDisplayPath(script)}`, ex ); diff --git a/src/notebooks/controllers/ipywidgets/scriptSourceProvider/cdnWidgetScriptSourceProvider.ts b/src/notebooks/controllers/ipywidgets/scriptSourceProvider/cdnWidgetScriptSourceProvider.ts index d76eaa3323f..9c1bb91d6b3 100644 --- a/src/notebooks/controllers/ipywidgets/scriptSourceProvider/cdnWidgetScriptSourceProvider.ts +++ b/src/notebooks/controllers/ipywidgets/scriptSourceProvider/cdnWidgetScriptSourceProvider.ts @@ -8,7 +8,7 @@ import { GLOBAL_MEMENTO, IConfigurationService, IMemento, WidgetCDNs } from '../ import { createDeferred, createDeferredFromPromise, Deferred } from '../../../../platform/common/utils/async'; import { Common, DataScience } from '../../../../platform/common/utils/localize'; import { noop } from '../../../../platform/common/utils/misc'; -import { traceError, traceTrace, traceInfoIfCI } from '../../../../platform/logging'; +import { logger } from '../../../../platform/logging'; import { ConsoleForegroundColors } from '../../../../platform/logging/types'; import { sendTelemetryEvent } from '../../../../telemetry'; import { IWidgetScriptSourceProvider, WidgetScriptSource } from '../types'; @@ -124,7 +124,7 @@ export class CDNWidgetScriptSourceProvider implements IWidgetScriptSourceProvide ): Promise { // If the webview is not online, then we cannot use the CDN. if (isWebViewOnline === false) { - traceInfoIfCI(`Webview is offline, cannot use CDN for ${moduleName}`); + logger.ci(`Webview is offline, cannot use CDN for ${moduleName}`); this.warnIfNoAccessToInternetFromWebView(moduleName).catch(noop); return { moduleName @@ -134,7 +134,7 @@ export class CDNWidgetScriptSourceProvider implements IWidgetScriptSourceProvide this.cdnProviders.length === 0 && this.globalMemento.get(GlobalStateKeyToTrackIfUserConfiguredCDNAtLeastOnce, false) ) { - traceInfoIfCI(`No CDN providers and user configured CDN`); + logger.ci(`No CDN providers and user configured CDN`); return { moduleName }; @@ -165,7 +165,7 @@ export class CDNWidgetScriptSourceProvider implements IWidgetScriptSourceProvide moduleName: string, moduleVersion: string ): Promise { - traceTrace( + logger.trace( `${ ConsoleForegroundColors.Green }Searching for Widget Script ${moduleName}#${moduleVersion} using cdns ${this.cdnProviders.join(' ')}` @@ -180,13 +180,13 @@ export class CDNWidgetScriptSourceProvider implements IWidgetScriptSourceProvide ); const scriptUri = uris.find((u) => u); if (scriptUri) { - traceTrace( + logger.trace( `${ConsoleForegroundColors.Green}Widget Script ${moduleName}#${moduleVersion} found at URI: ${scriptUri}` ); return { moduleName, scriptUri, source: 'cdn' }; } - traceError(`Widget Script ${moduleName}#${moduleVersion} was not found on on any cdn`); + logger.error(`Widget Script ${moduleName}#${moduleVersion} was not found on on any cdn`); this.handleWidgetSourceNotFound(moduleName, moduleVersion).catch(noop); return { moduleName }; } @@ -200,7 +200,7 @@ export class CDNWidgetScriptSourceProvider implements IWidgetScriptSourceProvide return downloadUrl; } } catch (ex) { - traceTrace(`Failed downloading ${moduleName}:${moduleVersion} from ${cdn}`); + logger.trace(`Failed downloading ${moduleName}:${moduleVersion} from ${cdn}`); return undefined; } } diff --git a/src/notebooks/controllers/ipywidgets/scriptSourceProvider/ipyWidgetScriptSource.ts b/src/notebooks/controllers/ipywidgets/scriptSourceProvider/ipyWidgetScriptSource.ts index f1bae624efb..b75bb161f96 100644 --- a/src/notebooks/controllers/ipywidgets/scriptSourceProvider/ipyWidgetScriptSource.ts +++ b/src/notebooks/controllers/ipywidgets/scriptSourceProvider/ipyWidgetScriptSource.ts @@ -3,7 +3,7 @@ import type * as jupyterlabService from '@jupyterlab/services'; import { Event, EventEmitter, NotebookDocument, Uri } from 'vscode'; -import { traceError, traceTrace, traceWarning } from '../../../../platform/logging'; +import { logger } from '../../../../platform/logging'; import { IDisposableRegistry, IConfigurationService, IDisposable } from '../../../../platform/common/types'; import { InteractiveWindowMessages, IPyWidgetMessages } from '../../../../messageTypes'; import { sendTelemetryEvent, Telemetry } from '../../../../telemetry'; @@ -132,7 +132,7 @@ export class IPyWidgetScriptSource { this.kernel.onDisposed(() => this.dispose()); this.handlePendingRequests(); this.sendBaseUrl(); - traceTrace('IPyWidgetScriptSource.initialize'); + logger.trace('IPyWidgetScriptSource.initialize'); } /** * Sends the base url of the remote Jupyter server to the webview. @@ -153,7 +153,7 @@ export class IPyWidgetScriptSource { }); } }) - .catch((ex) => traceError(`Failed to get baseUrl`, ex)); + .catch((ex) => logger.error(`Failed to get baseUrl`, ex)); } /** * Outputs like HTML and JavaScript can have references to widget scripts as well, @@ -181,7 +181,7 @@ export class IPyWidgetScriptSource { }); }); } catch (ex) { - traceWarning(`Failed to fetch script sources`, ex); + logger.warn(`Failed to fetch script sources`, ex); } finally { this.allWidgetScriptsSent = true; } @@ -189,9 +189,9 @@ export class IPyWidgetScriptSource { private async onRequestWidgetScript(payload: { moduleName: string; moduleVersion: string; requestId: string }) { const { moduleName, moduleVersion, requestId } = payload; - traceTrace(`${ConsoleForegroundColors.Green}Fetch Script for ${JSON.stringify(payload)}`); + logger.trace(`${ConsoleForegroundColors.Green}Fetch Script for ${JSON.stringify(payload)}`); await this.sendWidgetSource(moduleName, moduleVersion, requestId).catch((ex) => - traceError('Failed to send widget sources upon ready', ex) + logger.error('Failed to send widget sources upon ready', ex) ); // Ensure we send all of the widget script sources found in the `/share/jupyter/nbextensions` folder. @@ -199,8 +199,8 @@ export class IPyWidgetScriptSource { try { await this.sendWidgetScriptSources(); } finally { - this.sendWidgetSource(moduleName, moduleVersion, requestId).catch( - traceError.bind(undefined, 'Failed to send widget sources upon ready') + this.sendWidgetSource(moduleName, moduleVersion, requestId).catch((ex) => + logger.error('Failed to send widget sources upon ready', ex) ); } } @@ -221,17 +221,17 @@ export class IPyWidgetScriptSource { let widgetSource: WidgetScriptSource = { moduleName, requestId }; try { - traceTrace(`${ConsoleForegroundColors.Green}Fetch Script for ${moduleName}`); + logger.trace(`${ConsoleForegroundColors.Green}Fetch Script for ${moduleName}`); widgetSource = await this.scriptProvider.getWidgetScriptSource(moduleName, moduleVersion); // If we have a widget source from CDN, never overwrite that. if (this.widgetSources.get(widgetSource.moduleName)?.source !== 'cdn') { this.widgetSources.set(widgetSource.moduleName, widgetSource); } } catch (ex) { - traceError('Failed to get widget source due to an error', ex); + logger.error('Failed to get widget source due to an error', ex); sendTelemetryEvent(Telemetry.HashedIPyWidgetScriptDiscoveryError); } finally { - traceTrace( + logger.trace( `${ConsoleForegroundColors.Green}Script for ${moduleName}, is ${widgetSource.scriptUri} from ${widgetSource.source}` ); // Send to UI (even if there's an error) continues instead of hanging while waiting for a response. @@ -248,8 +248,8 @@ export class IPyWidgetScriptSource { if (moduleName) { const { moduleVersion, requestId } = this.pendingModuleRequests.get(moduleName)!; this.pendingModuleRequests.delete(moduleName); - this.sendWidgetSource(moduleName, moduleVersion, requestId).catch( - traceError.bind(`Failed to send WidgetScript for ${moduleName}`) + this.sendWidgetSource(moduleName, moduleVersion, requestId).catch((ex) => + logger.error(`Failed to send WidgetScript for ${moduleName}`, ex) ); } } diff --git a/src/notebooks/controllers/ipywidgets/scriptSourceProvider/ipyWidgetScriptSourceProvider.ts b/src/notebooks/controllers/ipywidgets/scriptSourceProvider/ipyWidgetScriptSourceProvider.ts index 974c26d3234..c292bd5c824 100644 --- a/src/notebooks/controllers/ipywidgets/scriptSourceProvider/ipyWidgetScriptSourceProvider.ts +++ b/src/notebooks/controllers/ipywidgets/scriptSourceProvider/ipyWidgetScriptSourceProvider.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { traceError, traceTrace, traceWarning } from '../../../../platform/logging'; +import { logger } from '../../../../platform/logging'; import { WidgetCDNs, IConfigurationService } from '../../../../platform/common/types'; import { sendTelemetryEvent, Telemetry } from '../../../../telemetry'; import { getTelemetrySafeHashedString } from '../../../../platform/telemetry/helpers'; @@ -89,20 +89,20 @@ export class IPyWidgetScriptSourceProvider extends DisposableBase implements IWi found = source; break; } else { - traceWarning( + logger.warn( `Widget Script Source not found for ${moduleName}@${moduleVersion} from ${scriptProvider.id}` ); } } this.sendTelemetryForWidgetModule(moduleName, moduleVersion, '', found.source).catch(noop); if (!found.scriptUri) { - traceError( + logger.error( `Script source for Widget ${moduleName}@${moduleVersion} not found in ${this.scriptProviders .map((item) => item.id) .join(', ')}` ); } else { - traceTrace( + logger.trace( `Script source for Widget ${moduleName}@${moduleVersion} was found from source ${found.source} and ${found.scriptUri}` ); } diff --git a/src/notebooks/controllers/ipywidgets/scriptSourceProvider/localIPyWidgetScriptManager.node.ts b/src/notebooks/controllers/ipywidgets/scriptSourceProvider/localIPyWidgetScriptManager.node.ts index aca6bf059fa..55ef5da8b8a 100644 --- a/src/notebooks/controllers/ipywidgets/scriptSourceProvider/localIPyWidgetScriptManager.node.ts +++ b/src/notebooks/controllers/ipywidgets/scriptSourceProvider/localIPyWidgetScriptManager.node.ts @@ -12,7 +12,7 @@ import { IKernel } from '../../../../kernels/types'; import { BaseIPyWidgetScriptManager } from './baseIPyWidgetScriptManager'; import { IIPyWidgetScriptManager, INbExtensionsPathProvider } from '../types'; import { JupyterPaths } from '../../../../kernels/raw/finder/jupyterPaths.node'; -import { traceWarning } from '../../../../platform/logging'; +import { logger } from '../../../../platform/logging'; type KernelConnectionId = string; /** @@ -70,7 +70,7 @@ export class LocalIPyWidgetScriptManager extends BaseIPyWidgetScriptManager impl const stopWatch = new StopWatch(); this.sourceNbExtensionsPath = await this.nbExtensionsPathProvider.getNbExtensionsParentPath(this.kernel); if (!this.sourceNbExtensionsPath) { - traceWarning(`No nbextensions folder found for kernel ${this.kernel.kernelConnectionMetadata.id}`); + logger.warn(`No nbextensions folder found for kernel ${this.kernel.kernelConnectionMetadata.id}`); return; } const kernelHash = await getTelemetrySafeHashedString(this.kernel.kernelConnectionMetadata.id); diff --git a/src/notebooks/controllers/ipywidgets/scriptSourceProvider/remoteIPyWidgetScriptManager.ts b/src/notebooks/controllers/ipywidgets/scriptSourceProvider/remoteIPyWidgetScriptManager.ts index 25ec96a2124..f1b91e8e1c8 100644 --- a/src/notebooks/controllers/ipywidgets/scriptSourceProvider/remoteIPyWidgetScriptManager.ts +++ b/src/notebooks/controllers/ipywidgets/scriptSourceProvider/remoteIPyWidgetScriptManager.ts @@ -5,7 +5,7 @@ import type * as nbformat from '@jupyterlab/nbformat'; import * as path from '../../../../platform/vscode-path/path'; import { ExtensionMode, Uri } from 'vscode'; import { IExtensionContext } from '../../../../platform/common/types'; -import { traceError, traceInfoIfCI, traceTrace } from '../../../../platform/logging'; +import { logger } from '../../../../platform/logging'; import { executeSilently, isPythonKernelConnection } from '../../../../kernels/helpers'; import { IKernel, RemoteKernelConnectionMetadata } from '../../../../kernels/types'; import { IIPyWidgetScriptManager } from '../types'; @@ -74,7 +74,7 @@ export class RemoteIPyWidgetScriptManager extends BaseIPyWidgetScriptManager imp const code = await this.getCodeToExecute(); if (!this.kernel.session?.kernel) { - traceInfoIfCI('No Kernel session to get list of widget entry points'); + logger.ci('No Kernel session to get list of widget entry points'); return []; } const promises: Promise[] = []; @@ -102,16 +102,16 @@ export class RemoteIPyWidgetScriptManager extends BaseIPyWidgetScriptManager imp const outputs = await Promise.race(promises); if (outputs.length === 0) { - traceInfoIfCI('Unable to get widget entry points, no outputs after running the code'); + logger.ci('Unable to get widget entry points, no outputs after running the code'); return []; } const output = outputs[0] as nbformat.IStream; if (output.output_type !== 'stream' || output.name !== 'stdout') { - traceInfoIfCI('Unable to get widget entry points, no stream/stdout outputs after running the code'); + logger.ci('Unable to get widget entry points, no stream/stdout outputs after running the code'); return []; } try { - traceTrace(`Widget Outputs include, ${output.text}`); + logger.trace(`Widget Outputs include, ${output.text}`); // Value will be an array of the form `['xyz', 'abc']` const items = (output.text as string) .trim() @@ -125,7 +125,7 @@ export class RemoteIPyWidgetScriptManager extends BaseIPyWidgetScriptManager imp widgetFolderName: path.dirname(item) })); } catch (ex) { - traceError(`Failed to parse output to get list of IPyWidgets, output is ${output.text}`, ex); + logger.error(`Failed to parse output to get list of IPyWidgets, output is ${output.text}`, ex); return []; } } @@ -136,9 +136,9 @@ export class RemoteIPyWidgetScriptManager extends BaseIPyWidgetScriptManager imp // If we fail to download using both mechanisms, then log an error. promise.catch((ex) => { httpClientResponse.catch((ex) => - traceError(`Failed to download widget script source from ${script.toString(true)}`, ex) + logger.error(`Failed to download widget script source from ${script.toString(true)}`, ex) ); - traceError(`Failed to download widget script source from ${script.toString(true)}`, ex); + logger.error(`Failed to download widget script source from ${script.toString(true)}`, ex); }); return promise; } diff --git a/src/notebooks/controllers/kernelConnector.ts b/src/notebooks/controllers/kernelConnector.ts index 7e4b20d00ab..8cebafe5d4f 100644 --- a/src/notebooks/controllers/kernelConnector.ts +++ b/src/notebooks/controllers/kernelConnector.ts @@ -14,7 +14,7 @@ import { IKernelController } from '../../kernels/types'; import { CancellationError, Memento, NotebookDocument, Uri, commands, window } from 'vscode'; -import { traceVerbose, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { Resource, IMemento, GLOBAL_MEMENTO, IDisplayOptions, IDisposable } from '../../platform/common/types'; import { createDeferred, createDeferredFromPromise, Deferred } from '../../platform/common/utils/async'; import { DataScience } from '../../platform/common/utils/localize'; @@ -270,7 +270,7 @@ export class KernelConnector { ); } - traceVerbose( + logger.debug( `${initialContext} the kernel, options.disableUI=${options.disableUI} for ${getDisplayPath( 'notebook' in notebookResource ? notebookResource.notebook.uri : notebookResource.resource )}` @@ -441,7 +441,7 @@ export class KernelConnector { } } catch (error) { if (!isCancellationError(error)) { - traceWarning( + logger.warn( `Error occurred while trying to ${currentContext} the kernel, options.disableUI=${options.disableUI}`, error ); diff --git a/src/notebooks/controllers/kernelSelector.ts b/src/notebooks/controllers/kernelSelector.ts index ed7dd5ac776..2e227d05ff5 100644 --- a/src/notebooks/controllers/kernelSelector.ts +++ b/src/notebooks/controllers/kernelSelector.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { traceError } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { Resource } from '../../platform/common/types'; import { INotebookEditorProvider } from '../types'; import { commands } from 'vscode'; @@ -19,6 +19,6 @@ export async function selectKernel( notebookEditor }) as Promise; } - traceError(`Unable to select kernel as the Notebook document could not be identified`); + logger.error(`Unable to select kernel as the Notebook document could not be identified`); return false; } diff --git a/src/notebooks/controllers/kernelSource/kernelSourceCommandHandler.ts b/src/notebooks/controllers/kernelSource/kernelSourceCommandHandler.ts index f775407e910..39e1feb8f75 100644 --- a/src/notebooks/controllers/kernelSource/kernelSourceCommandHandler.ts +++ b/src/notebooks/controllers/kernelSource/kernelSourceCommandHandler.ts @@ -38,7 +38,7 @@ import { IDisposable, IDisposableRegistry } from '../../../platform/common/types import { DataScience } from '../../../platform/common/utils/localize'; import { noop } from '../../../platform/common/utils/misc'; import { ServiceContainer } from '../../../platform/ioc/container'; -import { traceError, traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { INotebookEditorProvider } from '../../types'; import { IControllerRegistration, @@ -276,7 +276,7 @@ export class KernelSourceCommandHandler implements IExtensionSyncActivationServi notebook.notebookType as typeof JupyterNotebookView | typeof InteractiveWindowView ]); if (!Array.isArray(controllers) || controllers.length === 0) { - traceWarning(`No controller created for selected kernel connection ${kernel.kind}:${kernel.id}`); + logger.warn(`No controller created for selected kernel connection ${kernel.kind}:${kernel.id}`); return; } initializeInteractiveOrNotebookTelemetryBasedOnUserAction(notebook.uri, kernel) @@ -316,7 +316,7 @@ export class KernelSourceCommandHandler implements IExtensionSyncActivationServi installWithoutPrompting: true }); } catch (ex) { - traceError(`Failed to install missing dependencies for Conda kernel ${controller.connection.id}`, ex); + logger.error(`Failed to install missing dependencies for Conda kernel ${controller.connection.id}`, ex); } finally { dispose(disposables); } diff --git a/src/notebooks/controllers/kernelSource/localPythonEnvKernelSourceSelector.node.ts b/src/notebooks/controllers/kernelSource/localPythonEnvKernelSourceSelector.node.ts index b6fd973e71d..4de177718b7 100644 --- a/src/notebooks/controllers/kernelSource/localPythonEnvKernelSourceSelector.node.ts +++ b/src/notebooks/controllers/kernelSource/localPythonEnvKernelSourceSelector.node.ts @@ -23,7 +23,7 @@ import { InputFlowAction } from '../../../platform/common/utils/multiStepInput'; import { ILocalPythonNotebookKernelSourceSelector } from '../types'; import { ServiceContainer } from '../../../platform/ioc/container'; import { IInterpreterService } from '../../../platform/interpreter/contracts'; -import { traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { getDisplayPath } from '../../../platform/common/platform/fs-paths'; export type MultiStepResult = { @@ -127,11 +127,11 @@ export class LocalPythonEnvNotebookKernelSourceSelector const jupyterPaths = ServiceContainer.instance.get(JupyterPaths); const interpreter = await interpreters.getInterpreterDetails(env.path); if (!interpreter) { - traceWarning(`Python Env ${getDisplayPath(env.id)} not found}`); + logger.warn(`Python Env ${getDisplayPath(env.id)} not found}`); return; } if (!interpreter || this.filter.isPythonEnvironmentExcluded(interpreter)) { - traceWarning(`Python Env hidden via filter: ${getDisplayPath(interpreter.id)}`); + logger.warn(`Python Env hidden via filter: ${getDisplayPath(interpreter.id)}`); return; } diff --git a/src/notebooks/controllers/kernelSource/localPythonKernelSelector.node.ts b/src/notebooks/controllers/kernelSource/localPythonKernelSelector.node.ts index ffad1fb4b0b..a9fcb6eb17a 100644 --- a/src/notebooks/controllers/kernelSource/localPythonKernelSelector.node.ts +++ b/src/notebooks/controllers/kernelSource/localPythonKernelSelector.node.ts @@ -24,7 +24,7 @@ import { noop } from '../../../platform/common/utils/misc'; import { findPreferredPythonEnvironment } from '../preferredKernelConnectionService.node'; import { Commands } from '../../../platform/common/constants'; import { createDeferred } from '../../../platform/common/utils/async'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { DisposableBase } from '../../../platform/common/utils/lifecycle'; export class LocalPythonKernelSelector extends DisposableBase { @@ -142,7 +142,7 @@ export class LocalPythonKernelSelector extends DisposableBase { } }, (ex) => { - traceError(`Failed to install the Python extension`, ex); + logger.error(`Failed to install the Python extension`, ex); pythonExtensionNotInstalled.resolve(); } ); diff --git a/src/notebooks/controllers/kernelSource/quickPickKernelItemProvider.ts b/src/notebooks/controllers/kernelSource/quickPickKernelItemProvider.ts index 22edbf32a13..5b27f595838 100644 --- a/src/notebooks/controllers/kernelSource/quickPickKernelItemProvider.ts +++ b/src/notebooks/controllers/kernelSource/quickPickKernelItemProvider.ts @@ -9,7 +9,7 @@ import { getDisplayPath } from '../../../platform/common/platform/fs-paths'; import { IDisposable } from '../../../platform/common/types'; import { isPromise } from '../../../platform/common/utils/async'; import { DataScience } from '../../../platform/common/utils/localize'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { PythonEnvironmentFilter } from '../../../platform/interpreter/filter/filterService'; import { PreferredKernelConnectionService } from '../preferredKernelConnectionService'; import { IQuickPickKernelItemProvider } from './types'; @@ -50,7 +50,7 @@ export class QuickPickKernelItemProvider implements IQuickPickKernelItemProvider if (isPromise(finderPromise)) { finderPromise .then((finder) => this.setupFinder(finder)) - .catch((ex) => traceError(`Failed to setup finder for ${this.title}`, ex)); + .catch((ex) => logger.error(`Failed to setup finder for ${this.title}`, ex)); } else { this.setupFinder(finderPromise); } @@ -65,7 +65,7 @@ export class QuickPickKernelItemProvider implements IQuickPickKernelItemProvider this._onDidChangeStatus.fire(); } if (this.refreshInvoked) { - finder.refresh().catch((ex) => traceError(`Failed to refresh finder for ${this.title}`, ex)); + finder.refresh().catch((ex) => logger.error(`Failed to refresh finder for ${this.title}`, ex)); } else if ( // If we're dealing with remote and we are idle and there are no kernels, // then trigger a refresh. @@ -73,7 +73,7 @@ export class QuickPickKernelItemProvider implements IQuickPickKernelItemProvider finder.status === 'idle' && this.filteredKernels(finder.kernels).length === 0 ) { - finder.refresh().catch((ex) => traceError(`Failed to refresh finder for ${this.title}`, ex)); + finder.refresh().catch((ex) => logger.error(`Failed to refresh finder for ${this.title}`, ex)); } switch (finder.kind) { case ContributedKernelFinderKind.LocalKernelSpec: @@ -144,7 +144,7 @@ export class QuickPickKernelItemProvider implements IQuickPickKernelItemProvider this.recommended = kernel; this._onDidChangeRecommended.fire(); }) - .catch((ex) => traceError(`Preferred connection failure ${getDisplayPath(this.notebook.uri)}`, ex)); + .catch((ex) => logger.error(`Preferred connection failure ${getDisplayPath(this.notebook.uri)}`, ex)); } private computePreferredLocalKernel( finder: IContributedKernelFinder, @@ -169,7 +169,7 @@ export class QuickPickKernelItemProvider implements IQuickPickKernelItemProvider this.recommended = kernel; this._onDidChangeRecommended.fire(); }) - .catch((ex) => traceError(`Preferred connection failure ${getDisplayPath(this.notebook?.uri)}`, ex)); + .catch((ex) => logger.error(`Preferred connection failure ${getDisplayPath(this.notebook?.uri)}`, ex)); }; computePreferred(); finder.onDidChangeKernels(computePreferred, this, this.disposables); diff --git a/src/notebooks/controllers/kernelSource/remoteNotebookKernelSourceSelector.ts b/src/notebooks/controllers/kernelSource/remoteNotebookKernelSourceSelector.ts index 5943c3d501b..35cc0a69fa4 100644 --- a/src/notebooks/controllers/kernelSource/remoteNotebookKernelSourceSelector.ts +++ b/src/notebooks/controllers/kernelSource/remoteNotebookKernelSourceSelector.ts @@ -46,7 +46,7 @@ import { JupyterConnection } from '../../../kernels/jupyter/connection/jupyterCo import { generateIdFromRemoteProvider } from '../../../kernels/jupyter/jupyterUtils'; import { BaseProviderBasedQuickPick } from '../../../platform/common/providerBasedQuickPick'; import { PreferredKernelConnectionService } from '../preferredKernelConnectionService'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IRemoteKernelFinderController } from '../../../kernels/jupyter/finder/types'; import { raceCancellationError } from '../../../platform/common/cancellation'; import { JupyterServer, JupyterServerCollection, JupyterServerCommand } from '../../../api'; @@ -417,7 +417,7 @@ export class RemoteNotebookKernelSourceSelector implements IRemoteNotebookKernel state.notebook, Promise.resolve(selectedSource.kernelFinderInfo as IRemoteKernelFinder), token - ).catch((ex) => traceError(`Failed to select a kernel`, ex)); + ).catch((ex) => logger.error(`Failed to select a kernel`, ex)); if (result && result === InputFlowAction.back) { if (selectedSource === defaultSelection) { throw InputFlowAction.back; @@ -447,7 +447,7 @@ export class RemoteNotebookKernelSourceSelector implements IRemoteNotebookKernel })(); const result = await this.selectRemoteKernelFromPicker(state.notebook, finderPromise, token).catch( - (ex) => traceError(`Failed to select a kernel`, ex) + (ex) => logger.error(`Failed to select a kernel`, ex) ); if (result && result === InputFlowAction.back) { if (selectedSource === defaultSelection) { @@ -521,7 +521,7 @@ export class RemoteNotebookKernelSourceSelector implements IRemoteNotebookKernel })(); const result = await this.selectRemoteKernelFromPicker(state.notebook, finderPromise, token).catch((ex) => - traceError(`Failed to select a kernel`, ex) + logger.error(`Failed to select a kernel`, ex) ); if (result && result === InputFlowAction.back) { // Do not go back to the previous command, @@ -578,7 +578,7 @@ export class RemoteNotebookKernelSourceSelector implements IRemoteNotebookKernel } remoteKernelPicker.selected = item; }) - .catch((ex) => traceError(`Failed to determine preferred remote kernel`, ex)); + .catch((ex) => logger.error(`Failed to determine preferred remote kernel`, ex)); return remoteKernelPicker.selectItem(token); } } diff --git a/src/notebooks/controllers/liveKernelSwitcher.ts b/src/notebooks/controllers/liveKernelSwitcher.ts index 0908bf29d5d..8ee3c0cebe8 100644 --- a/src/notebooks/controllers/liveKernelSwitcher.ts +++ b/src/notebooks/controllers/liveKernelSwitcher.ts @@ -4,7 +4,7 @@ import { inject, injectable } from 'inversify'; import { NotebookDocument, commands, window, workspace } from 'vscode'; import { IExtensionSyncActivationService } from '../../platform/activation/types'; -import { traceVerbose, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IDisposableRegistry } from '../../platform/common/types'; import { PreferredRemoteKernelIdProvider } from '../../kernels/jupyter/connection/preferredRemoteKernelIdProvider'; import { KernelConnectionMetadata } from '../../kernels/types'; @@ -86,7 +86,7 @@ export class LiveKernelSwitcher implements IExtensionSyncActivationService { } private async switchKernel(n: NotebookDocument, kernel: Readonly) { - traceVerbose(`Using notebook.selectKernel to force remote kernel for ${getDisplayPath(n.uri)} to ${kernel.id}`); + logger.debug(`Using notebook.selectKernel to force remote kernel for ${getDisplayPath(n.uri)} to ${kernel.id}`); // Do this in a loop as it may fail await commands.executeCommand('notebook.selectKernel', { id: kernel.id, @@ -107,9 +107,9 @@ export class LiveKernelSwitcher implements IExtensionSyncActivationService { 100 ); if (success) { - traceVerbose(`Successfully switched remote kernel for ${getDisplayPath(n.uri)} to ${kernel.id}`); + logger.debug(`Successfully switched remote kernel for ${getDisplayPath(n.uri)} to ${kernel.id}`); } else { - traceWarning(`Failed to switch remote kernel for ${getDisplayPath(n.uri)} to ${kernel.id}`); + logger.warn(`Failed to switch remote kernel for ${getDisplayPath(n.uri)} to ${kernel.id}`); } } } diff --git a/src/notebooks/controllers/notebookIPyWidgetCoordinator.ts b/src/notebooks/controllers/notebookIPyWidgetCoordinator.ts index 8357287d684..ae44561119e 100644 --- a/src/notebooks/controllers/notebookIPyWidgetCoordinator.ts +++ b/src/notebooks/controllers/notebookIPyWidgetCoordinator.ts @@ -4,7 +4,7 @@ import { inject, injectable } from 'inversify'; import { NotebookDocument, Disposable, NotebookEditor, Uri, EventEmitter, workspace, window } from 'vscode'; import { dispose } from '../../platform/common/utils/lifecycle'; -import { traceTrace } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { getDisplayPath } from '../../platform/common/platform/fs-paths'; import { IDisposableRegistry, IDisposable } from '../../platform/common/types'; import { IServiceContainer } from '../../platform/ioc/types'; @@ -142,7 +142,7 @@ export class NotebookIPyWidgetCoordinator implements IExtensionSyncActivationSer } const notebook = editor.notebook; if (!controller) { - traceTrace( + logger.trace( `No controller, hence notebook communications cannot be initialized for editor ${getDisplayPath( editor.notebook.uri )}` diff --git a/src/notebooks/controllers/pythonEnvKernelConnectionCreator.node.ts b/src/notebooks/controllers/pythonEnvKernelConnectionCreator.node.ts index c951bd82466..1d6f0a73414 100644 --- a/src/notebooks/controllers/pythonEnvKernelConnectionCreator.node.ts +++ b/src/notebooks/controllers/pythonEnvKernelConnectionCreator.node.ts @@ -16,7 +16,7 @@ import { getDisplayPath } from '../../platform/common/platform/fs-paths'; import { IDisposable } from '../../platform/common/types'; import { IInterpreterService } from '../../platform/interpreter/contracts'; import { ServiceContainer } from '../../platform/ioc/container'; -import { traceVerbose, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { PythonEnvironment } from '../../platform/pythonEnvironments/info'; import { sendTelemetryEvent, Telemetry } from '../../telemetry'; import { IControllerRegistration } from './types'; @@ -86,7 +86,7 @@ export class PythonEnvKernelConnectionCreator { return { action: 'Cancel' }; } env = envResult.interpreter; - traceVerbose(`Python Environment created ${env.id}`); + logger.debug(`Python Environment created ${env.id}`); const kernelConnection = await this.waitForPythonKernel(envResult.interpreter); if (this.cancelTokeSource.token.isCancellationRequested) { @@ -98,10 +98,10 @@ export class PythonEnvKernelConnectionCreator { failed: true, reason: 'kernelConnectionNotCreated' }); - traceVerbose(`Python Environment ${env.id} not found as a kernel`); + logger.debug(`Python Environment ${env.id} not found as a kernel`); return { action: 'Cancel' }; } - traceVerbose(`Python Environment ${env.id} found as a kernel ${kernelConnection.kind}:${kernelConnection.id}`); + logger.debug(`Python Environment ${env.id} found as a kernel ${kernelConnection.kind}:${kernelConnection.id}`); const dependencyService = ServiceContainer.instance.get(IKernelDependencyService); const result = await dependencyService.installMissingDependencies({ resource: this.notebook.uri, @@ -115,7 +115,7 @@ export class PythonEnvKernelConnectionCreator { let dependenciesInstalled = true; if (result !== KernelInterpreterDependencyResponse.ok) { dependenciesInstalled = false; - traceWarning( + logger.warn( `Dependencies not installed for new Python Env ${getDisplayPath(env.uri)} for notebook ${getDisplayPath( this.notebook.uri )}` @@ -177,7 +177,7 @@ export class PythonEnvKernelConnectionCreator { return; } if (!kernel) { - traceWarning(`New Python Environment ${getDisplayPath(env.uri)} not found as a kernel`); + logger.warn(`New Python Environment ${getDisplayPath(env.uri)} not found as a kernel`); } return kernel; }); @@ -201,19 +201,19 @@ export class PythonEnvKernelConnectionCreator { return { action: 'Cancel' }; } if (!path) { - traceWarning( + logger.warn( `Python Environment not created, either user cancelled the creation or there was an error in the Python Extension` ); return { action: 'Cancel' }; } this.createdEnvId = path; - traceVerbose(`Python Environment created ${path}`); + logger.debug(`Python Environment created ${path}`); const env = await interpreterService.getInterpreterDetails({ path }); if (this.cancelTokeSource.token.isCancellationRequested) { return { action: 'Cancel' }; } if (!env) { - traceWarning(`No interpreter details for New Python Environment ${getDisplayPath(Uri.file(path))}`); + logger.warn(`No interpreter details for New Python Environment ${getDisplayPath(Uri.file(path))}`); } this.createdEnvId = env?.id; return { interpreter: env }; diff --git a/src/notebooks/controllers/remoteKernelConnectionHandler.ts b/src/notebooks/controllers/remoteKernelConnectionHandler.ts index ed75ae2227c..6f92aae1e1a 100644 --- a/src/notebooks/controllers/remoteKernelConnectionHandler.ts +++ b/src/notebooks/controllers/remoteKernelConnectionHandler.ts @@ -7,7 +7,7 @@ import { IControllerRegistration, IVSCodeNotebookController } from './types'; import { IExtensionSyncActivationService } from '../../platform/activation/types'; import { IDisposableRegistry } from '../../platform/common/types'; import { noop } from '../../platform/common/utils/misc'; -import { traceVerbose } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IKernel, IKernelProvider, isLocalConnection } from '../../kernels/types'; import { PreferredRemoteKernelIdProvider } from '../../kernels/jupyter/connection/preferredRemoteKernelIdProvider'; import { ILiveRemoteKernelConnectionUsageTracker } from '../../kernels/jupyter/types'; @@ -77,7 +77,7 @@ export class RemoteKernelConnectionHandler implements IExtensionSyncActivationSe const storeKernelInfo = () => { const kernelId = kernel.session?.kernel?.id; if (!kernel.disposed && !kernel.disposing && kernelId) { - traceVerbose(`Updating preferred kernel for remote notebook ${kernelId}`); + logger.debug(`Updating preferred kernel for remote notebook ${kernelId}`); this.preferredRemoteKernelIdProvider.storePreferredRemoteKernelId(resource, kernelId).catch(noop); this.liveKernelTracker.trackKernelIdAsUsed(resource, serverId, kernelId); } diff --git a/src/notebooks/controllers/remoteKernelControllerWatcher.ts b/src/notebooks/controllers/remoteKernelControllerWatcher.ts index 83450a6be04..6dc0357d6ce 100644 --- a/src/notebooks/controllers/remoteKernelControllerWatcher.ts +++ b/src/notebooks/controllers/remoteKernelControllerWatcher.ts @@ -7,7 +7,7 @@ import { isLocalConnection } from '../../kernels/types'; import { IExtensionSyncActivationService } from '../../platform/activation/types'; import { IDisposableRegistry } from '../../platform/common/types'; import { noop } from '../../platform/common/utils/misc'; -import { traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IControllerRegistration } from './types'; import { JupyterServerCollection, JupyterServerProvider } from '../../api'; import { CancellationTokenSource } from 'vscode'; @@ -100,7 +100,7 @@ export class RemoteKernelControllerWatcher implements IExtensionSyncActivationSe } if (!validServerIds.includes(connection.serverProviderHandle.handle)) { // Looks like the 3rd party provider has updated its handles and this server is no longer available. - traceWarning( + logger.warn( `Deleting controller ${controller.id} as it is associated with a server Id that has been removed` ); controller.dispose(); @@ -118,7 +118,7 @@ export class RemoteKernelControllerWatcher implements IExtensionSyncActivationSe return; } // Looks like the 3rd party provider has updated its handles and this server is no longer available. - traceWarning( + logger.warn( `Deleting controller ${controller.id} as it is associated with a Provider Id that has been removed` ); controller.dispose(); diff --git a/src/notebooks/controllers/vscodeNotebookController.ts b/src/notebooks/controllers/vscodeNotebookController.ts index 65f3d54f518..be24dfa778b 100644 --- a/src/notebooks/controllers/vscodeNotebookController.ts +++ b/src/notebooks/controllers/vscodeNotebookController.ts @@ -24,7 +24,7 @@ import { import { IPythonExtensionChecker } from '../../platform/api/types'; import { Exiting, InteractiveWindowView, JupyterNotebookView, PYTHON_LANGUAGE } from '../../platform/common/constants'; import { dispose } from '../../platform/common/utils/lifecycle'; -import { traceInfoIfCI, traceInfo, traceVerbose, traceWarning, traceError } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { getDisplayPath } from '../../platform/common/platform/fs-paths'; import { IConfigurationService, @@ -178,7 +178,7 @@ export class VSCodeNotebookController implements Disposable, IVSCodeNotebookCont try { controller.controller.variableProvider = jupyterVairablesProvider; } catch (ex) { - traceWarning('Failed to attach variable provider', ex); + logger.warn('Failed to attach variable provider', ex); } return controller; @@ -307,7 +307,7 @@ export class VSCodeNotebookController implements Disposable, IVSCodeNotebookCont // eslint-disable-next-line @typescript-eslint/no-explicit-any public postMessage(message: any, editor?: NotebookEditor): Thenable { const messageType = message && 'message' in message ? message.message : ''; - traceInfoIfCI(`${ConsoleForegroundColors.Green}Posting message to Notebook UI ${messageType}`); + logger.ci(`${ConsoleForegroundColors.Green}Posting message to Notebook UI ${messageType}`); return this.controller.postMessage(message, editor); } /** @@ -330,12 +330,12 @@ export class VSCodeNotebookController implements Disposable, IVSCodeNotebookCont const nbDocumentUris = workspace.notebookDocuments .filter((item) => this.associatedDocuments.has(item)) .map((item) => item.uri.toString()); - traceVerbose( + logger.debug( `Disposing controller ${this.id} associated with connection ${this.connection.id} ${ nbDocumentUris.length ? 'and documents ' + nbDocumentUris.join(', ') : '' }` ); - traceInfoIfCI( + logger.ci( `Disposing controller ${this.id} associated with connection ${this.connection.id} ${ nbDocumentUris.length ? 'and documents ' + nbDocumentUris.join(', ') : '' } called from ${new Error('').stack}` @@ -378,7 +378,7 @@ export class VSCodeNotebookController implements Disposable, IVSCodeNotebookCont // See here https://github.com/microsoft/vscode-jupyter/runs/5581627878?check_suite_focus=true cells = cells.filter((cell) => { if (cell.index < 0) { - traceWarning( + logger.warn( `Attempting to run a cell with index ${cell.index}, kind ${ cell.kind }, text = ${cell.document.getText()}` @@ -392,14 +392,14 @@ export class VSCodeNotebookController implements Disposable, IVSCodeNotebookCont if (!workspace.isTrusted) { return; } - traceVerbose(`Handle Execution of Cells ${cells.map((c) => c.index)} for ${getDisplayPath(notebook.uri)}`); + logger.debug(`Handle Execution of Cells ${cells.map((c) => c.index)} for ${getDisplayPath(notebook.uri)}`); await initializeInteractiveOrNotebookTelemetryBasedOnUserAction(notebook.uri, this.connection); telemetryTracker?.stop(); // Notebook is trusted. Continue to execute cells await Promise.all(cells.map((cell) => this.executeCell(notebook, cell))); } private async onDidChangeSelectedNotebooks(event: { notebook: NotebookDocument; selected: boolean }) { - traceInfoIfCI( + logger.ci( `NotebookController selection event called for notebook ${event.notebook.uri.toString()} & controller ${ this.connection.kind }:${this.id}. Selected ${event.selected} ` @@ -414,7 +414,7 @@ export class VSCodeNotebookController implements Disposable, IVSCodeNotebookCont // Possible user selected a controller that's not contributed by us at all. const kernel = this.kernelProvider.get(event.notebook); if (kernel?.kernelConnectionMetadata.id === this.kernelConnection.id) { - traceInfo( + logger.info( `Disposing kernel ${this.kernelConnection.id} for notebook ${getDisplayPath( event.notebook.uri )} due to selection of another kernel or closing of the notebook` @@ -439,7 +439,7 @@ export class VSCodeNotebookController implements Disposable, IVSCodeNotebookCont ); void warnWhenUsingOutdatedPython(this.kernelConnection); const deferred = createDeferred(); - traceInfoIfCI( + logger.ci( `Controller ${this.connection.kind}:${this.id} associated with nb ${getDisplayPath(event.notebook.uri)}` ); this.associatedDocuments.set(event.notebook, deferred.promise); @@ -449,7 +449,7 @@ export class VSCodeNotebookController implements Disposable, IVSCodeNotebookCont // If this NotebookController was selected, fire off the event this._onNotebookControllerSelected.fire({ notebook: event.notebook, controller: this }); this._onNotebookControllerSelectionChanged.fire(event); - traceVerbose(`Controller selection change completed`); + logger.debug(`Controller selection change completed`); deferred.resolve(); } @@ -513,11 +513,11 @@ export class VSCodeNotebookController implements Disposable, IVSCodeNotebookCont } private handleInterrupt(notebook: NotebookDocument) { - traceVerbose(`VS Code interrupted kernel for ${getDisplayPath(notebook.uri)}`); + logger.debug(`VS Code interrupted kernel for ${getDisplayPath(notebook.uri)}`); notebook.getCells().forEach((cell) => traceCellMessage(cell, 'Cell cancellation requested')); commands .executeCommand(Commands.InterruptKernel, { notebookEditor: { notebookUri: notebook.uri } }) - .then(noop, (ex) => traceError('Failed to interrupt', ex)); + .then(noop, (ex) => logger.error('Failed to interrupt', ex)); } private createCellExecutionIfNecessary(cell: NotebookCell, controller: IKernelController) { @@ -597,7 +597,7 @@ export class VSCodeNotebookController implements Disposable, IVSCodeNotebookCont return; } if (!isCancellationError(ex)) { - traceError(`Error in execution`, ex); + logger.error(`Error in execution`, ex); } if (!kernelStarted) { exec.start(); @@ -674,7 +674,7 @@ export class VSCodeNotebookController implements Disposable, IVSCodeNotebookCont existingKernel && areKernelConnectionsEqual(existingKernel.kernelConnectionMetadata, selectedKernelConnectionMetadata) ) { - traceInfo('Switch kernel did not change kernel.'); + logger.info('Switch kernel did not change kernel.'); return; } @@ -710,7 +710,7 @@ export class VSCodeNotebookController implements Disposable, IVSCodeNotebookCont controller: this.controller, resourceUri: document.uri // In the case of interactive window, we cannot pass the Uri of notebook, it must be the Py file or undefined. }); - traceVerbose(`KernelProvider switched kernel to id = ${newKernel.kernelConnectionMetadata.id}`); + logger.debug(`KernelProvider switched kernel to id = ${newKernel.kernelConnectionMetadata.id}`); // If this is a Python notebook and Python isn't installed, then don't auto-start the kernel. if (isPythonKernelConnection(this.kernelConnection) && !this.extensionChecker.isPythonExtensionInstalled) { diff --git a/src/notebooks/debugger/controllers/debugCellController.ts b/src/notebooks/debugger/controllers/debugCellController.ts index f7a28d4b5f1..3e3ccf10997 100644 --- a/src/notebooks/debugger/controllers/debugCellController.ts +++ b/src/notebooks/debugger/controllers/debugCellController.ts @@ -5,7 +5,7 @@ import { NotebookCell, commands } from 'vscode'; import { DebugProtocol } from 'vscode-debugprotocol'; import { INotebookKernelExecution } from '../../../kernels/types'; import { noop } from '../../../platform/common/utils/misc'; -import { traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { sendTelemetryEvent } from '../../../telemetry'; import { DebuggingTelemetry } from '../constants'; import { IDebuggingDelegate, IKernelDebugAdapter } from '../debuggingTypes'; @@ -32,7 +32,7 @@ export class DebugCellController implements IDebuggingDelegate { } private trace(tag: string, msg: string) { - traceVerbose(`[Debug-Cell] ${tag}: ${msg}`); + logger.debug(`[Debug-Cell] ${tag}: ${msg}`); } public async willSendEvent(msg: DebugProtocol.Event): Promise { diff --git a/src/notebooks/debugger/controllers/resetKernelController.ts b/src/notebooks/debugger/controllers/resetKernelController.ts index 381c3bb17da..2f9047ba73a 100644 --- a/src/notebooks/debugger/controllers/resetKernelController.ts +++ b/src/notebooks/debugger/controllers/resetKernelController.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { DebugProtocol } from 'vscode-debugprotocol'; -import { traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IDebuggingDelegate, IKernelDebugAdapter } from '../debuggingTypes'; /** @@ -12,7 +12,7 @@ export class ResetKernelController implements IDebuggingDelegate { constructor(private readonly debugAdapter: IKernelDebugAdapter) {} private trace(tag: string, msg: string) { - traceVerbose(`[Debug-Reset] ${tag}: ${msg}`); + logger.debug(`[Debug-Reset] ${tag}: ${msg}`); } public async willSendRequest(request: DebugProtocol.Request): Promise { diff --git a/src/notebooks/debugger/controllers/restartController.ts b/src/notebooks/debugger/controllers/restartController.ts index b0bb124aa50..b31fe737623 100644 --- a/src/notebooks/debugger/controllers/restartController.ts +++ b/src/notebooks/debugger/controllers/restartController.ts @@ -4,7 +4,7 @@ import { NotebookCell } from 'vscode'; import { DebugProtocol } from 'vscode-debugprotocol'; import { IServiceContainer } from '../../../platform/ioc/types'; -import { traceError, traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IDebuggingDelegate, IKernelDebugAdapter, INotebookDebuggingManager, KernelDebugMode } from '../debuggingTypes'; /** @@ -23,11 +23,11 @@ export class RestartController implements IDebuggingDelegate { } private trace(tag: string, msg: string) { - traceVerbose(`[Debug-Restart] ${tag}: ${msg}`); + logger.debug(`[Debug-Restart] ${tag}: ${msg}`); } private error(tag: string, msg: string) { - traceError(`[Debug-Restart] ${tag}: ${msg}`); + logger.error(`[Debug-Restart] ${tag}: ${msg}`); } public async willSendResponse(response: DebugProtocol.Response): Promise { diff --git a/src/notebooks/debugger/controllers/runByLineController.ts b/src/notebooks/debugger/controllers/runByLineController.ts index c33af3b1185..0b4bbb3dcf6 100644 --- a/src/notebooks/debugger/controllers/runByLineController.ts +++ b/src/notebooks/debugger/controllers/runByLineController.ts @@ -9,7 +9,7 @@ import { splitLines } from '../../../platform/common/helpers'; import { IConfigurationService } from '../../../platform/common/types'; import { parseForComments } from '../../../platform/common/utils'; import { noop } from '../../../platform/common/utils/misc'; -import { traceInfoIfCI, traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import * as path from '../../../platform/vscode-path/path'; import { sendTelemetryEvent } from '../../../telemetry'; import { DebuggingTelemetry } from '../constants'; @@ -35,7 +35,7 @@ export class RunByLineController implements IDebuggingDelegate { public continue(): void { if (typeof this.lastPausedThreadId !== 'number') { - traceVerbose(`No paused thread, can't do RBL`); + logger.debug(`No paused thread, can't do RBL`); this.stop(); return; } @@ -44,7 +44,7 @@ export class RunByLineController implements IDebuggingDelegate { } public stop(): void { - traceInfoIfCI(`RunbylineController::stop()`); + logger.ci(`RunbylineController::stop()`); // When debugpy gets stuck, running a cell fixes it and allows us to start another debugging session this.execution.executeHidden('pass').then(noop, noop); this.debugAdapter.disconnect().then(noop, noop); @@ -75,7 +75,7 @@ export class RunByLineController implements IDebuggingDelegate { } public async willSendRequest(request: DebugProtocol.Request): Promise { - traceInfoIfCI(`willSendRequest: ${request.command}`); + logger.ci(`willSendRequest: ${request.command}`); if (request.command === 'configurationDone') { await this.initializeExecute(); } @@ -114,7 +114,7 @@ export class RunByLineController implements IDebuggingDelegate { } private trace(tag: string, msg: string) { - traceVerbose(`[Debug-RBL] ${tag}: ${msg}`); + logger.debug(`[Debug-RBL] ${tag}: ${msg}`); } private async initializeExecute() { diff --git a/src/notebooks/debugger/debuggerVariables.ts b/src/notebooks/debugger/debuggerVariables.ts index 26f904297a6..7bed368a290 100644 --- a/src/notebooks/debugger/debuggerVariables.ts +++ b/src/notebooks/debugger/debuggerVariables.ts @@ -29,7 +29,7 @@ import { Resource } from '../../platform/common/types'; import { noop } from '../../platform/common/utils/misc'; -import { traceError, traceVerbose } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { sendTelemetryEvent, Telemetry } from '../../telemetry'; import { IJupyterDebugService, INotebookDebuggingManager, KernelDebugMode } from './debuggingTypes'; import { DebugLocationTracker } from './debugLocationTracker'; @@ -339,7 +339,7 @@ export class DebuggerVariables context: 'repl', format: { rawString: true } }; - traceVerbose(`Evaluating in debugger : ${this.debugService.activeDebugSession.id}: ${code}`); + logger.debug(`Evaluating in debugger : ${this.debugService.activeDebugSession.id}: ${code}`); try { if (initializeCode) { await this.debugService.activeDebugSession.customRequest('evaluate', { @@ -354,7 +354,7 @@ export class DebuggerVariables if (results && results.result !== 'None') { return results; } else { - traceError(`Cannot evaluate ${code}`); + logger.error(`Cannot evaluate ${code}`); return undefined; } } finally { diff --git a/src/notebooks/debugger/debuggingManager.ts b/src/notebooks/debugger/debuggingManager.ts index bd695344a9c..f0bfd3a5c75 100644 --- a/src/notebooks/debugger/debuggingManager.ts +++ b/src/notebooks/debugger/debuggingManager.ts @@ -24,7 +24,7 @@ import { IConfigurationService } from '../../platform/common/types'; import { DataScience } from '../../platform/common/utils/localize'; import { noop } from '../../platform/common/utils/misc'; import { IServiceContainer } from '../../platform/ioc/types'; -import { traceInfo } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import * as path from '../../platform/vscode-path/path'; import { sendTelemetryEvent } from '../../telemetry'; import { IControllerRegistration } from '../controllers/types'; @@ -108,12 +108,12 @@ export class DebuggingManager } public async tryToStartDebugging(mode: KernelDebugMode, cell: NotebookCell, skipIpykernelCheck = false) { - traceInfo(`Starting debugging with mode ${mode}`); + logger.info(`Starting debugging with mode ${mode}`); if (!skipIpykernelCheck) { const ipykernelResult = await this.checkIpykernelAndPrompt(cell); if (ipykernelResult !== IpykernelCheckResult.Ok) { - traceInfo(`Ipykernel check failed: ${IpykernelCheckResult[ipykernelResult]}`); + logger.info(`Ipykernel check failed: ${IpykernelCheckResult[ipykernelResult]}`); return; } } @@ -173,17 +173,17 @@ export class DebuggingManager const notebook = workspace.notebookDocuments.find((doc) => doc.uri.toString() === notebookUri); if (!notebook) { - traceInfo(`Cannot start debugging. Notebook ${notebookUri} not found.`); + logger.info(`Cannot start debugging. Notebook ${notebookUri} not found.`); return; } if (this.notebookInProgress.has(notebook)) { - traceInfo(`Cannot start debugging. Already debugging this notebook`); + logger.info(`Cannot start debugging. Already debugging this notebook`); return; } if (this.isDebugging(notebook)) { - traceInfo(`Cannot start debugging. Already debugging this notebook document.`); + logger.info(`Cannot start debugging. Already debugging this notebook document.`); return; } diff --git a/src/notebooks/debugger/debuggingManagerBase.ts b/src/notebooks/debugger/debuggingManagerBase.ts index 4fb72a36839..e337a77fb3e 100644 --- a/src/notebooks/debugger/debuggingManagerBase.ts +++ b/src/notebooks/debugger/debuggingManagerBase.ts @@ -20,7 +20,7 @@ import { IKernel, IKernelProvider, isRemoteConnection } from '../../kernels/type import { IDisposable } from '../../platform/common/types'; import { DataScience } from '../../platform/common/utils/localize'; import { noop } from '../../platform/common/utils/misc'; -import { traceError, traceInfo, traceInfoIfCI } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { sendTelemetryEvent } from '../../telemetry'; import { IControllerRegistration } from '../controllers/types'; import { DebuggingTelemetry } from './constants'; @@ -98,12 +98,12 @@ export abstract class DebuggingManagerBase implements IDisposable, IDebuggingMan } protected async startDebuggingConfig(config: INotebookDebugConfig, options?: DebugSessionOptions) { - traceInfoIfCI(`Attempting to start debugging with config ${JSON.stringify(config)}`); + logger.ci(`Attempting to start debugging with config ${JSON.stringify(config)}`); try { await debug.startDebugging(undefined, config, options); } catch (err) { - traceError(`Can't start debugging (${err})`); + logger.error(`Can't start debugging (${err})`); window.showErrorMessage(DataScience.cantStartDebugging).then(noop, noop); } } @@ -114,7 +114,7 @@ export abstract class DebuggingManagerBase implements IDisposable, IDebuggingMan } protected async endSession(session: DebugSession) { - traceInfo(`Ending debug session ${session.id}`); + logger.info(`Ending debug session ${session.id}`); this._doneDebugging.fire(); for (const [doc, dbg] of this.notebookToDebugger.entries()) { if (dbg && session.id === dbg.session.id) { @@ -221,7 +221,7 @@ export abstract class DebuggingManagerBase implements IDisposable, IDebuggingMan }); return result; } catch (ex) { - traceError('Debugging: Could not check for ipykernel 6', ex); + logger.error('Debugging: Could not check for ipykernel 6', ex); } return IpykernelCheckResult.Unknown; } diff --git a/src/notebooks/debugger/jupyterDebugService.node.ts b/src/notebooks/debugger/jupyterDebugService.node.ts index 99dd278b2bc..db920a1c603 100644 --- a/src/notebooks/debugger/jupyterDebugService.node.ts +++ b/src/notebooks/debugger/jupyterDebugService.node.ts @@ -23,7 +23,7 @@ import { WorkspaceFolder } from 'vscode'; import { DebugProtocol } from 'vscode-debugprotocol'; -import { traceInfo, traceError } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IDisposable, IDisposableRegistry } from '../../platform/common/types'; import { createDeferred } from '../../platform/common/utils/async'; import { noop } from '../../platform/common/utils/misc'; @@ -276,17 +276,17 @@ export class JupyterDebugService implements IJupyterDebugService, IDisposable { } private async sendStartSequence(config: DebugConfiguration, sessionId: string): Promise { - traceInfo('Sending debugger initialize...'); + logger.info('Sending debugger initialize...'); await this.sendInitialize(); if (this._breakpoints.length > 0) { - traceInfo('Sending breakpoints'); + logger.info('Sending breakpoints'); await this.sendBreakpoints(); } - traceInfo('Sending debugger attach...'); + logger.info('Sending debugger attach...'); const attachPromise = this.sendAttach(config, sessionId); - traceInfo('Sending configuration done'); + logger.info('Sending configuration done'); await this.sendConfigurationDone(); - traceInfo('Session started.'); + logger.info('Session started.'); return attachPromise.then(() => { this.sessionStartedEvent.fire(this.session!); }); @@ -352,14 +352,14 @@ export class JupyterDebugService implements IJupyterDebugService, IDisposable { this.protocolParser.on(`response_${command}`, (resp: any) => { if (resp.request_seq === sequenceNumber) { this.sendToTrackers(resp); - traceInfo(`Received response from debugger: ${JSON.stringify(args)}`); + logger.info(`Received response from debugger: ${JSON.stringify(args)}`); disposable.dispose(); response.resolve(resp.body); } }); this.socket?.on('error', (err) => response.reject(err)); // NOSONAR this.emitMessage(command, args).catch((exc) => { - traceError(`Exception attempting to emit ${command} to debugger: `, exc); + logger.error(`Exception attempting to emit ${command} to debugger: `, exc); }); return response.promise; } @@ -376,7 +376,7 @@ export class JupyterDebugService implements IJupyterDebugService, IDisposable { }; this.sequence += 1; const objString = JSON.stringify(obj); - traceInfo(`Sending request to debugger: ${objString}`); + logger.info(`Sending request to debugger: ${objString}`); const message = `Content-Length: ${objString.length}\r\n\r\n${objString}`; this.socket.write(message, (_a: any) => { this.sendToTrackers(obj); @@ -400,12 +400,12 @@ export class JupyterDebugService implements IJupyterDebugService, IDisposable { private onOutput(args: any): void { this.sendToTrackers(args); - traceInfo(JSON.stringify(args)); + logger.info(JSON.stringify(args)); } private onError(args: any): void { this.sendToTrackers(args); - traceInfo(JSON.stringify(args)); + logger.info(JSON.stringify(args)); } private onClose(): void { diff --git a/src/notebooks/debugger/kernelDebugAdapter.ts b/src/notebooks/debugger/kernelDebugAdapter.ts index fa6e1df684d..fd488a0b65c 100644 --- a/src/notebooks/debugger/kernelDebugAdapter.ts +++ b/src/notebooks/debugger/kernelDebugAdapter.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { DebugProtocol } from 'vscode-debugprotocol'; -import { traceError } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import * as path from '../../platform/vscode-path/path'; import { IDumpCellResponse } from './debuggingTypes'; import { KernelDebugAdapterBase } from './kernelDebugAdapterBase'; @@ -24,7 +24,7 @@ export class KernelDebugAdapter extends KernelDebugAdapterBase { this.fileToCell.set(norm, cell.document.uri); this.cellToFile.set(cell.document.uri.toString(), norm); } catch (err) { - traceError(err); + logger.error(err); } } protected translateRealLocationToDebuggerLocation(location: { diff --git a/src/notebooks/debugger/kernelDebugAdapterBase.ts b/src/notebooks/debugger/kernelDebugAdapterBase.ts index d48ca3cb2ad..3ca69d92b9d 100644 --- a/src/notebooks/debugger/kernelDebugAdapterBase.ts +++ b/src/notebooks/debugger/kernelDebugAdapterBase.ts @@ -23,7 +23,7 @@ import { IDebugService } from '../../platform/common/application/types'; import { IPlatformService } from '../../platform/common/platform/types'; import { IDisposable } from '../../platform/common/types'; import { noop } from '../../platform/common/utils/misc'; -import { traceError, traceInfo, traceInfoIfCI, traceVerbose, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import * as path from '../../platform/vscode-path/path'; import { sendTelemetryEvent } from '../../telemetry'; import { DebuggingTelemetry } from './constants'; @@ -71,7 +71,7 @@ export abstract class KernelDebugAdapterBase implements DebugAdapter, IKernelDeb private readonly platformService: IPlatformService, private readonly debugService: IDebugService ) { - traceInfoIfCI(`Creating kernel debug adapter for debugging notebooks`); + logger.ci(`Creating kernel debug adapter for debugging notebooks`); const configuration = this.session.configuration; assertIsDebugConfig(configuration); this.configuration = configuration; @@ -145,11 +145,11 @@ export abstract class KernelDebugAdapterBase implements DebugAdapter, IKernelDeb } private trace(tag: string, msg: string) { - traceVerbose(`[Debug] ${tag}: ${msg}`); + logger.debug(`[Debug] ${tag}: ${msg}`); } async onIOPubMessage(_: unknown, msg: KernelMessage.IIOPubMessage) { - traceInfoIfCI(`Debug IO Pub message: ${JSON.stringify(msg)}`); + logger.ci(`Debug IO Pub message: ${JSON.stringify(msg)}`); if (isDebugEventMsg(msg)) { this.trace('event', JSON.stringify(msg)); for (const d of this.delegates ?? []) { @@ -171,7 +171,7 @@ export abstract class KernelDebugAdapterBase implements DebugAdapter, IKernelDeb protected async handleClientMessageAsync(message: DebugProtocol.ProtocolMessage): Promise { try { - traceInfoIfCI(`KernelDebugAdapter::handleMessage ${JSON.stringify(message, undefined, ' ')}`); + logger.ci(`KernelDebugAdapter::handleMessage ${JSON.stringify(message, undefined, ' ')}`); // Necessary, since dumpCell usually runs before debugging starts? if (message.type === 'request' && (message as DebugProtocol.Request).command === 'setBreakpoints') { @@ -199,7 +199,7 @@ export abstract class KernelDebugAdapterBase implements DebugAdapter, IKernelDeb await this.sendMessageToJupyterSession(message); } catch (e) { - traceError(`KernelDebugAdapter::handleMessage failure: ${e}`); + logger.error(`KernelDebugAdapter::handleMessage failure: ${e}`); } } @@ -239,12 +239,12 @@ export abstract class KernelDebugAdapterBase implements DebugAdapter, IKernelDeb try { await Promise.all([ this.deleteDumpedFiles().catch((ex) => - traceWarning('Error deleting temporary debug files.', ex) + logger.warn('Error deleting temporary debug files.', ex) ), this.session.customRequest('disconnect', { restart: false }) ]); } catch (e) { - traceError(`Failed to disconnect debug session`, e); + logger.error(`Failed to disconnect debug session`, e); } } this.endSession.fire(this.session); @@ -293,7 +293,7 @@ export abstract class KernelDebugAdapterBase implements DebugAdapter, IKernelDeb protected async sendMessageToJupyterSession(message: DebugProtocol.ProtocolMessage) { if (this.jupyterSession.isDisposed || this.jupyterSession.status === 'dead' || !this.jupyterSession.kernel) { - traceInfo(`Skipping sending message ${message.type} because session is disposed`); + logger.info(`Skipping sending message ${message.type} because session is disposed`); return; } @@ -318,7 +318,7 @@ export abstract class KernelDebugAdapterBase implements DebugAdapter, IKernelDeb return control.done; } else { // cannot send via iopub, no way to handle events even if they existed - traceError(`Unknown message type to send ${message.type}`); + logger.error(`Unknown message type to send ${message.type}`); } } diff --git a/src/notebooks/export/exportBase.web.ts b/src/notebooks/export/exportBase.web.ts index df3c0ec8928..85bee10aad1 100644 --- a/src/notebooks/export/exportBase.web.ts +++ b/src/notebooks/export/exportBase.web.ts @@ -14,7 +14,7 @@ import { concatMultilineString } from '../../platform/common/utils'; import { IFileSystem } from '../../platform/common/platform/types'; import { PythonEnvironment } from '../../platform/pythonEnvironments/info'; import { ExportFormat, IExportBase, IExportUtil } from './types'; -import { traceError, traceVerbose } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { reportAction } from '../../platform/progress/decorator'; import { ReportableAction } from '../../platform/progress/types'; import { SessionDisposedError } from '../../platform/errors/sessionDisposedError'; @@ -138,7 +138,7 @@ export class ExportBase implements IExportBase { throw new Error(text || `Failed to export to ${format}`); } else if (text) { // trace the output in case we didn't identify all errors - traceVerbose(text); + logger.debug(text); } if (format === ExportFormat.pdf) { @@ -188,7 +188,7 @@ export class ExportBase implements IExportBase { backingFileDir.length && backingFileDir !== '.' ? `${backingFileDir}/${newName}` : newName // Note, the docs say the path uses UNIX delimiters. ); } catch (exc) { - traceError(`Backing file not supported: ${exc}`); + logger.error(`Backing file not supported: ${exc}`); } if (backingFile) { diff --git a/src/notebooks/export/fileConverter.ts b/src/notebooks/export/fileConverter.ts index ba37826d911..bcc495cd9bd 100644 --- a/src/notebooks/export/fileConverter.ts +++ b/src/notebooks/export/fileConverter.ts @@ -8,7 +8,7 @@ import { Telemetry } from '../../platform/common/constants'; import { IConfigurationService } from '../../platform/common/types'; import * as localize from '../../platform/common/utils/localize'; import { noop } from '../../platform/common/utils/misc'; -import { traceError } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { ProgressReporter } from '../../platform/progress/progressReporter'; import { PythonEnvironment } from '../../platform/pythonEnvironments/info'; import { ExportFileOpener } from './exportFileOpener'; @@ -77,11 +77,11 @@ export abstract class FileConverterBase implements IFileConverter { } await this.performExport(format, sourceDocument, target, token, candidateInterpreter); } catch (e) { - traceError('Export failed', e); + logger.error('Export failed', e); sendTelemetryEvent(Telemetry.ExportNotebookAsFailed, undefined, { format: format }); if (format === ExportFormat.pdf) { - traceError(localize.DataScience.exportToPDFDependencyMessage); + logger.error(localize.DataScience.exportToPDFDependencyMessage); } this.showExportFailed(localize.DataScience.exportFailedGeneralMessage); diff --git a/src/notebooks/languages/emptyNotebookCellLanguageService.ts b/src/notebooks/languages/emptyNotebookCellLanguageService.ts index cd8fc788ae1..39660d65b80 100644 --- a/src/notebooks/languages/emptyNotebookCellLanguageService.ts +++ b/src/notebooks/languages/emptyNotebookCellLanguageService.ts @@ -5,7 +5,7 @@ import { inject, injectable } from 'inversify'; import { languages, NotebookCellKind, NotebookDocument, window } from 'vscode'; import { IExtensionSyncActivationService } from '../../platform/activation/types'; import { PYTHON_LANGUAGE } from '../../platform/common/constants'; -import { traceError } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IDisposableRegistry } from '../../platform/common/types'; import { noop } from '../../platform/common/utils/misc'; import { chainWithPendingUpdates } from '../../kernels/execution/notebookUpdater'; @@ -69,7 +69,7 @@ export class EmptyNotebookCellLanguageService implements IExtensionSyncActivatio break; } default: { - traceError(`Unsupported kernel kind encountered ${kernelKind}`); + logger.error(`Unsupported kernel kind encountered ${kernelKind}`); return; } } diff --git a/src/notebooks/languages/helpers.ts b/src/notebooks/languages/helpers.ts index 23d8c033bd2..aa450e81e35 100644 --- a/src/notebooks/languages/helpers.ts +++ b/src/notebooks/languages/helpers.ts @@ -4,7 +4,7 @@ import { NotebookCellKind, NotebookDocument } from 'vscode'; import { getLanguageInNotebookMetadata } from '../../kernels/helpers'; import { getNotebookMetadata } from '../../platform/common/utils'; -import { traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; // Get the language of the notebook document, preference given to metadata over the language of // the first cell @@ -17,6 +17,6 @@ export function getLanguageOfNotebookDocument(doc: NotebookDocument): string | u // Fall back to the language of the first code cell in the notebook. return language || doc.getCells().find((cell) => cell.kind === NotebookCellKind.Code)?.document.languageId; } catch (ex) { - traceWarning('Failed to determine language of first cell', ex); + logger.warn('Failed to determine language of first cell', ex); } } diff --git a/src/notebooks/notebookCommandListener.ts b/src/notebooks/notebookCommandListener.ts index 15a477106fb..9da3b6ba996 100644 --- a/src/notebooks/notebookCommandListener.ts +++ b/src/notebooks/notebookCommandListener.ts @@ -22,7 +22,7 @@ import { DisplayOptions } from '../kernels/displayOptions'; import { IKernel, IKernelProvider } from '../kernels/types'; import { getDisplayPath } from '../platform/common/platform/fs-paths'; import { DataScience } from '../platform/common/utils/localize'; -import { traceInfo, traceVerbose } from '../platform/logging'; +import { logger } from '../platform/logging'; import { INotebookEditorProvider } from './types'; import { IServiceContainer } from '../platform/ioc/types'; import { endCellAndDisplayErrorsInCell } from '../kernels/execution/helpers'; @@ -129,11 +129,11 @@ export class NotebookCommandListener implements IDataScienceCommandListener { if (document === undefined) { return; } - traceVerbose(`Command interrupted kernel for ${getDisplayPath(document.uri)}`); + logger.debug(`Command interrupted kernel for ${getDisplayPath(document.uri)}`); const kernel = this.kernelProvider.get(document); if (!kernel) { - traceInfo(`Interrupt requested & no kernel.`); + logger.info(`Interrupt requested & no kernel.`); return; } await this.wrapKernelMethod('interrupt', kernel); @@ -169,7 +169,7 @@ export class NotebookCommandListener implements IDataScienceCommandListener { const kernel = this.kernelProvider.get(document); if (kernel) { - traceVerbose(`Restart kernel command handler for ${getDisplayPath(document.uri)}`); + logger.debug(`Restart kernel command handler for ${getDisplayPath(document.uri)}`); if (await this.shouldAskForRestart(document.uri)) { // Ask the user if they want us to restart or not. const message = DataScience.restartKernelMessage; diff --git a/src/notebooks/outputs/tracebackFormatter.ts b/src/notebooks/outputs/tracebackFormatter.ts index 5b44e51eaa4..4ac597d5962 100644 --- a/src/notebooks/outputs/tracebackFormatter.ts +++ b/src/notebooks/outputs/tracebackFormatter.ts @@ -7,7 +7,7 @@ import { ITracebackFormatter } from '../../kernels/types'; import { JupyterNotebookView } from '../../platform/common/constants'; import { getFilePath } from '../../platform/common/platform/fs-paths'; import { DataScience } from '../../platform/common/utils/localize'; -import { traceInfoIfCI } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IConfigurationService } from '../../platform/common/types'; const LineNumberMatchRegex = /(;32m[ ->]*?)(\d+)(.*)/g; @@ -53,7 +53,7 @@ export class NotebookTracebackFormatter implements ITracebackFormatter { return `${prefix}${num}${suffix}\n`; }); - traceInfoIfCI(`Trace frame to match: ${traceFrame}`); + logger.ci(`Trace frame to match: ${traceFrame}`); const tracebackLinkify = (traceFrame: string, line: string) => { // We have a match, replace source lines first diff --git a/src/platform/api/pythonApi.ts b/src/platform/api/pythonApi.ts index a9990838e67..fc490f4517b 100644 --- a/src/platform/api/pythonApi.ts +++ b/src/platform/api/pythonApi.ts @@ -21,7 +21,7 @@ import { sendTelemetryEvent } from '../../telemetry'; import { isCI, PythonExtension, Telemetry } from '../common/constants'; import { IDisposableRegistry, IExtensionContext } from '../common/types'; import { createDeferred, sleep } from '../common/utils/async'; -import { traceError, traceInfoIfCI, traceVerbose, traceWarning } from '../logging'; +import { logger } from '../logging'; import { getDisplayPath, getFilePath } from '../common/platform/fs-paths'; import { IInterpreterService } from '../interpreter/contracts'; import { areInterpreterPathsSame, getInterpreterHash } from '../pythonEnvironments/info/interpreter'; @@ -72,7 +72,7 @@ export function pythonEnvToJupyterEnv(env: Environment): PythonEnvironment | und ? Uri.joinPath(env.environment?.folderUri || Uri.file(env.path), 'python.exe') : Uri.joinPath(env.environment?.folderUri || Uri.file(env.path), 'bin', 'python'); } else { - traceWarning(`Python environment ${getDisplayPath(env.id)} excluded as Uri is undefined`); + logger.warn(`Python environment ${getDisplayPath(env.id)} excluded as Uri is undefined`); return; } } else { @@ -199,7 +199,7 @@ export class OldPythonApiProvider implements IPythonApiProvider { await promise; activated = true; } catch (ex) { - traceError(`Failed activating the python extension: `, ex); + logger.error(`Failed activating the python extension: `, ex); this.api.reject(new PythonExtensionActicationFailedError(ex)); return; } @@ -212,7 +212,7 @@ export class OldPythonApiProvider implements IPythonApiProvider { this.didActivatePython.fire(); } if (!pythonExtension.exports?.jupyter) { - traceError(`Python extension is not exporting the jupyter API`); + logger.error(`Python extension is not exporting the jupyter API`); this.api.reject(new PythonExtensionApiNotExportedError()); } else { pythonExtension.exports.jupyter.registerHooks(); @@ -378,9 +378,9 @@ export class InterpreterService implements IInterpreterService { try { await api.environments.refreshEnvironments({ forceRefresh }); this.hookupOnDidChangeInterpreterEvent(); - traceVerbose(`Refreshed Environments`); + logger.debug(`Refreshed Environments`); } catch (ex) { - traceError(`Failed to refresh the list of interpreters`); + logger.error(`Failed to refresh the list of interpreters`); } })(); this.refreshPromises.push(promise); @@ -436,7 +436,7 @@ export class InterpreterService implements IInterpreterService { } }) .catch((ex) => { - traceWarning(`Failed to get active interpreter from Python for workspace ${workspaceId}`, ex); + logger.warn(`Failed to get active interpreter from Python for workspace ${workspaceId}`, ex); }); if (isCI || [ExtensionMode.Development, ExtensionMode.Test].includes(this.context.extensionMode)) { promise @@ -448,7 +448,7 @@ export class InterpreterService implements IInterpreterService { } this.lastLoggedResourceAndInterpreterId = key; const version = getCachedVersion(item); - traceVerbose( + logger.debug( `Active Interpreter ${resource ? `for '${getDisplayPath(resource)}' ` : ''}is ${getDisplayPath( item?.id )} (${item && getEnvironmentType(item)}, '${ @@ -496,7 +496,7 @@ export class InterpreterService implements IInterpreterService { if (matchedPythonEnv) { const env = await api.environments.resolveEnvironment(matchedPythonEnv); const resolved = this.trackResolvedEnvironment(env); - traceInfoIfCI( + logger.ci( `Interpreter details for ${pythonPathForLogging} from Python is ${JSON.stringify( env )} and our mapping is ${JSON.stringify(resolved)}` @@ -507,7 +507,7 @@ export class InterpreterService implements IInterpreterService { // Reduce excessive logging. if (!this.loggedEnvsWithoutInterpreterPath.has(key)) { this.loggedEnvsWithoutInterpreterPath.add(key); - traceWarning( + logger.warn( `No interpreter with path ${pythonPathForLogging} found in Python API, will convert Uri path to string as Id ${pythonPathForLogging}` ); } @@ -521,7 +521,7 @@ export class InterpreterService implements IInterpreterService { return this.trackResolvedEnvironment(env); }); } catch (ex) { - traceWarning( + logger.warn( `Failed to get Python interpreter details from Python Extension API for ${ typeof pythonPath === 'string' ? pythonPath @@ -600,7 +600,7 @@ export class InterpreterService implements IInterpreterService { this.eventHandlerAdded = true; api.environments.onDidEnvironmentVariablesChange( (e) => { - traceVerbose(`Detected changes to env file ${e.resource?.uri?.path} in PythonApi`); + logger.debug(`Detected changes to env file ${e.resource?.uri?.path} in PythonApi`); this._onDidEnvironmentVariablesChange.fire(); }, this, @@ -608,7 +608,7 @@ export class InterpreterService implements IInterpreterService { ); api.environments.onDidChangeActiveEnvironmentPath( () => { - traceVerbose(`Detected change in Active Python environment via Python API`); + logger.debug(`Detected change in Active Python environment via Python API`); this.workspaceCachedActiveInterpreter.clear(); this.triggerEventIfAllowed('interpreterChangeEvent', undefined); }, @@ -617,7 +617,7 @@ export class InterpreterService implements IInterpreterService { ); api.environments.onDidChangeEnvironments( async (e) => { - traceVerbose(`Python API env change detected, ${e.type} => '${e.env.id}'`); + logger.debug(`Python API env change detected, ${e.type} => '${e.env.id}'`); // Remove items that are no longer valid. if (e.type === 'remove') { this.triggerEventIfAllowed('interpreterChangeEvent', undefined); diff --git a/src/platform/common/application/debugService.ts b/src/platform/common/application/debugService.ts index 9e732265cc3..eee607fbcac 100644 --- a/src/platform/common/application/debugService.ts +++ b/src/platform/common/application/debugService.ts @@ -14,7 +14,7 @@ import { Event, WorkspaceFolder } from 'vscode'; -import { traceInfoIfCI } from '../../logging'; +import { logger } from '../../logging'; import { IDebugService } from './types'; /** @@ -27,7 +27,7 @@ export class DebugService implements IDebugService { return debug.activeDebugConsole; } public get activeDebugSession(): DebugSession | undefined { - traceInfoIfCI(`Getting active debug session, ${debug.activeDebugSession?.name}`); + logger.ci(`Getting active debug session, ${debug.activeDebugSession?.name}`); return debug.activeDebugSession; } public get breakpoints(): readonly Breakpoint[] { diff --git a/src/platform/common/application/encryptedStorage.ts b/src/platform/common/application/encryptedStorage.ts index 8442079bc90..3b19375fc72 100644 --- a/src/platform/common/application/encryptedStorage.ts +++ b/src/platform/common/application/encryptedStorage.ts @@ -4,7 +4,7 @@ import { inject, injectable } from 'inversify'; import { ExtensionMode } from 'vscode'; import { isCI } from '../constants'; -import { traceError } from '../../logging'; +import { logger } from '../../logging'; import { IExtensionContext } from '../types'; import { IEncryptedStorage } from './types'; @@ -29,7 +29,7 @@ export class EncryptedStorage implements IEncryptedStorage { try { await this.extensionContext.secrets.delete(`${service}.${key}`); } catch (e) { - traceError(e); + logger.error(e); } } else { await this.extensionContext.secrets.store(`${service}.${key}`, value); @@ -50,7 +50,7 @@ export class EncryptedStorage implements IEncryptedStorage { await this.extensionContext.secrets.delete(`${service}.${key}`); return; } catch (e) { - traceError(e); + logger.error(e); } } } diff --git a/src/platform/common/application/extensions.node.ts b/src/platform/common/application/extensions.node.ts index ecd116a27fe..c89982cdc9f 100644 --- a/src/platform/common/application/extensions.node.ts +++ b/src/platform/common/application/extensions.node.ts @@ -7,7 +7,7 @@ import { IDisposableRegistry, IExtensions } from '../types'; import { DataScience } from '../utils/localize'; import { parseStack } from '../../errors'; import { JVSC_EXTENSION_ID, unknownExtensionId } from '../constants'; -import { traceError } from '../../logging'; +import { logger } from '../../logging'; /** * Provides functions for tracking the list of extensions that VS code has installed (besides our own) @@ -102,13 +102,13 @@ export class Extensions implements IExtensions { } } } - traceError(`Unable to determine the caller of the extension API for trace stack`, stack); - traceError(`Jupyter Root`, jupyterExtRoot); - traceError(`Frames`, frames); + logger.error(`Unable to determine the caller of the extension API for trace stack`, stack); + logger.error(`Jupyter Root`, jupyterExtRoot); + logger.error(`Frames`, frames); return { extensionId: unknownExtensionId, displayName: DataScience.unknownPackage }; } catch (ex) { - traceError(`Unable to determine the caller of the extension API for trace stack.`, stack); - traceError(`Failure error`, ex); + logger.error(`Unable to determine the caller of the extension API for trace stack.`, stack); + logger.error(`Failure error`, ex); return { extensionId: unknownExtensionId, displayName: DataScience.unknownPackage }; } } diff --git a/src/platform/common/application/extensions.web.ts b/src/platform/common/application/extensions.web.ts index 5c3813c511e..af027fb2101 100644 --- a/src/platform/common/application/extensions.web.ts +++ b/src/platform/common/application/extensions.web.ts @@ -7,7 +7,7 @@ import { IExtensions } from '../types'; import { DataScience } from '../utils/localize'; import { JVSC_EXTENSION_ID, unknownExtensionId } from '../constants'; import { parseStack } from '../../errors'; -import { traceError } from '../../logging'; +import { logger } from '../../logging'; /** * Provides functions for tracking the list of extensions that VS code has installed (besides our own) @@ -43,7 +43,7 @@ export class Extensions implements IExtensions { return { extensionId: matchingExt.id, displayName: matchingExt.packageJSON.displayName }; } } - traceError(`Unable to determine the caller of the extension API for trace stack.`, stack); + logger.error(`Unable to determine the caller of the extension API for trace stack.`, stack); } return { extensionId: unknownExtensionId, displayName: DataScience.unknownPackage }; } diff --git a/src/platform/common/configMigration.ts b/src/platform/common/configMigration.ts index de5c6ec9665..0333c32d8a6 100644 --- a/src/platform/common/configMigration.ts +++ b/src/platform/common/configMigration.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { ConfigurationTarget, WorkspaceConfiguration } from 'vscode'; -import { traceWarning } from '../logging'; +import { logger } from '../logging'; import { noop } from './utils/misc'; import { PYTHON_LANGUAGE } from './constants'; @@ -138,5 +138,5 @@ export class ConfigMigration { } function handleSettingMigrationFailure(e: Error) { - traceWarning('Error migrating Jupyter configuration', e); + logger.warn('Error migrating Jupyter configuration', e); } diff --git a/src/platform/common/experiments/service.ts b/src/platform/common/experiments/service.ts index 60983c42937..c2c54daadee 100644 --- a/src/platform/common/experiments/service.ts +++ b/src/platform/common/experiments/service.ts @@ -6,7 +6,7 @@ import { Memento, workspace } from 'vscode'; import { getExperimentationService, IExperimentationService, TargetPopulation } from 'vscode-tas-client'; import { IApplicationEnvironment } from '../application/types'; import { JVSC_EXTENSION_ID, isPreReleaseVersion } from '../constants'; -import { traceInfo } from '../../logging'; +import { logger } from '../../logging'; import { GLOBAL_MEMENTO, IConfigurationService, IExperimentService, IJupyterSettings, IMemento } from '../types'; import { Experiments } from '../utils/localize'; import { Experiments as ExperimentGroups } from '../types'; @@ -156,17 +156,17 @@ export class ExperimentService implements IExperimentService { const telemetrySettings = workspace.getConfiguration('telemetry'); let experimentsDisabled = false; if (telemetrySettings && telemetrySettings.get('enableTelemetry') === false) { - traceInfo('Telemetry is disabled'); + logger.info('Telemetry is disabled'); experimentsDisabled = true; } if (telemetrySettings && telemetrySettings.get('telemetryLevel') === 'off') { - traceInfo('Telemetry level is off'); + logger.info('Telemetry level is off'); experimentsDisabled = true; } if (experimentsDisabled) { - traceInfo('Experiments are disabled, only manually opted experiments are active.'); + logger.info('Experiments are disabled, only manually opted experiments are active.'); } if (this._optOutFrom.includes('All')) { @@ -178,7 +178,7 @@ export class ExperimentService implements IExperimentService { } if (this._optInto.includes('All')) { // Only if 'All' is not in optOut then check if it is in Opt In. - traceInfo(Experiments.inGroup('All')); + logger.info(Experiments.inGroup('All')); // Similar to the opt out case. If user is opting into to all experiments we short // circuit the experiment checks. So, skip printing any additional details to the logs. @@ -192,7 +192,7 @@ export class ExperimentService implements IExperimentService { this._optOutFrom .filter((exp) => exp !== 'All') .forEach((exp) => { - traceInfo(Experiments.notInGroup(exp)); + logger.info(Experiments.notInGroup(exp)); }); // Log experiments that users manually opt into, these are experiments which are added using the exp framework. @@ -200,7 +200,7 @@ export class ExperimentService implements IExperimentService { .filter((exp) => exp !== 'All') .forEach((exp) => { enabledExperiments.add(exp); - traceInfo(Experiments.inGroup(exp)); + logger.info(Experiments.inGroup(exp)); }); if ( @@ -208,7 +208,7 @@ export class ExperimentService implements IExperimentService { !enabledExperiments.has(ExperimentGroups.DoNotWaitForZmqPortsToBeUsed) && (getVSCodeChannel() === 'insiders' || isPreReleaseVersion()) ) { - traceInfo(Experiments.inGroup(ExperimentGroups.DoNotWaitForZmqPortsToBeUsed)); + logger.info(Experiments.inGroup(ExperimentGroups.DoNotWaitForZmqPortsToBeUsed)); } if (!experimentsDisabled) { @@ -222,7 +222,7 @@ export class ExperimentService implements IExperimentService { !this._optInto.includes(exp) ) { optedIntoExperiments.add(exp); - traceInfo(Experiments.inGroup(exp)); + logger.info(Experiments.inGroup(exp)); } }); } diff --git a/src/platform/common/featureManager.ts b/src/platform/common/featureManager.ts index b2fa6799963..a824a56da3c 100644 --- a/src/platform/common/featureManager.ts +++ b/src/platform/common/featureManager.ts @@ -3,7 +3,7 @@ import { inject, injectable } from 'inversify'; import { Disposable, EventEmitter, WorkspaceConfiguration, commands, window, workspace } from 'vscode'; -import { traceVerbose } from '../logging'; +import { logger } from '../logging'; import { openInBrowser } from './net/browser'; import { Deprecated } from './utils/localize'; import { @@ -140,7 +140,7 @@ export class FeatureManager implements IFeaturesManager { if (notify) { this.notifyDeprecation(deprecatedInfo).catch((ex) => - traceVerbose('Jupyter Extension: notifyDeprecation', ex) + logger.debug('Jupyter Extension: notifyDeprecation', ex) ); } } diff --git a/src/platform/common/net/httpClient.ts b/src/platform/common/net/httpClient.ts index ad5a083fb05..721300663bd 100644 --- a/src/platform/common/net/httpClient.ts +++ b/src/platform/common/net/httpClient.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { IHttpClient } from '../types'; -import { traceVerbose } from '../../logging'; +import { logger } from '../../logging'; import * as fetch from 'cross-fetch'; import { workspace } from 'vscode'; @@ -29,7 +29,7 @@ export class HttpClient implements IHttpClient { const response = await this.downloadFile(uri); return response.status === 200; } catch (ex) { - traceVerbose(`HttpClient - Failure checking for file ${uri}: ${ex}`); + logger.debug(`HttpClient - Failure checking for file ${uri}: ${ex}`); return false; } } diff --git a/src/platform/common/platform/fileSystem.ts b/src/platform/common/platform/fileSystem.ts index e3dd9194bd2..229e97dc8aa 100644 --- a/src/platform/common/platform/fileSystem.ts +++ b/src/platform/common/platform/fileSystem.ts @@ -6,7 +6,7 @@ import * as vscode from 'vscode'; import { IFileSystem } from './types'; import * as uriPath from '../../vscode-path/resources'; import { isFileNotFoundError } from './errors'; -import { traceError } from '../../logging'; +import { logger } from '../../logging'; import { computeHash } from '../crypto'; import { HttpClient } from '../net/httpClient'; @@ -82,7 +82,7 @@ export class FileSystem implements IFileSystem { if (isFileNotFoundError(err)) { return false; } - traceError(`stat() failed for "${filename}"`, err); + logger.error(`stat() failed for "${filename}"`, err); return false; } diff --git a/src/platform/common/platform/linuxDistro.node.ts b/src/platform/common/platform/linuxDistro.node.ts index 9f56254a1ed..58fa44c85bb 100644 --- a/src/platform/common/platform/linuxDistro.node.ts +++ b/src/platform/common/platform/linuxDistro.node.ts @@ -4,7 +4,7 @@ import * as fs from 'fs-extra'; import * as os from 'os'; import { splitLines } from '../helpers'; -import { traceError } from '../../logging'; +import { logger } from '../../logging'; export type DistroInfo = { id: string; version_id: string; @@ -115,7 +115,7 @@ export async function getDistroInfo(): Promise { } }); } catch (ex) { - traceError(`Failed to read distro info`, ex); + logger.error(`Failed to read distro info`, ex); } return distro; diff --git a/src/platform/common/process/logger.node.ts b/src/platform/common/process/logger.node.ts index c56ce3a3b82..293443cc25c 100644 --- a/src/platform/common/process/logger.node.ts +++ b/src/platform/common/process/logger.node.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { traceInfo } from '../../logging'; +import { logger } from '../../logging'; import { Logging } from '../utils/localize'; import { SpawnOptions } from './types.node'; import { getDisplayPath } from '../platform/fs-paths.node'; @@ -27,5 +27,5 @@ export function logProcess(file: string, args: string[], options?: SpawnOptions) if (options && options.cwd) { message.push(` > ${Logging.currentWorkingDirectory} ${getDisplayPath(options.cwd.toString())}`); } - traceInfo(message.join('\n')); + logger.info(message.join('\n')); } diff --git a/src/platform/common/process/proc.node.ts b/src/platform/common/process/proc.node.ts index 08fd8907ec0..b39165127f3 100644 --- a/src/platform/common/process/proc.node.ts +++ b/src/platform/common/process/proc.node.ts @@ -3,7 +3,7 @@ import { exec, execSync, spawn } from 'child_process'; import { CancellationError, Disposable, EventEmitter } from 'vscode'; -import { ignoreLogging, traceDecoratorVerbose, traceInfoIfCI } from '../../logging'; +import { ignoreLogging, debugDecorator, logger } from '../../logging'; import { TraceOptions } from '../../logging/types'; import { IDisposable } from '../types'; import { createDeferred } from '../utils/async'; @@ -82,7 +82,7 @@ export class ProcessService implements IProcessService { const spawnOptions = this.getDefaultOptions(options); const proc = spawn(file, args, spawnOptions); let procExited = false; - traceInfoIfCI(`Exec observable ${file}, ${args.join(' ')}`); + logger.ci(`Exec observable ${file}, ${args.join(' ')}`); const disposables: IDisposable[] = []; const disposable: IDisposable = { // eslint-disable-next-line @@ -212,7 +212,7 @@ export class ProcessService implements IProcessService { return deferred.promise; } - @traceDecoratorVerbose('Execing shell command', TraceOptions.BeforeCall | TraceOptions.Arguments) + @debugDecorator('Execing shell command', TraceOptions.BeforeCall | TraceOptions.Arguments) public shellExec(command: string, @ignoreLogging() options: ShellOptions = {}): Promise> { const shellOptions = this.getDefaultOptions(options); return new Promise((resolve, reject) => { diff --git a/src/platform/common/process/processFactory.node.ts b/src/platform/common/process/processFactory.node.ts index 66451124916..7c1e3679ec2 100644 --- a/src/platform/common/process/processFactory.node.ts +++ b/src/platform/common/process/processFactory.node.ts @@ -3,7 +3,7 @@ import { inject, injectable } from 'inversify'; import { CancellationToken, workspace } from 'vscode'; -import { traceDecoratorVerbose } from '../../logging'; +import { debugDecorator } from '../../logging'; import { TraceOptions } from '../../logging/types'; import { Resource } from '../types'; import { ICustomEnvironmentVariablesProvider } from '../variables/types'; @@ -20,7 +20,7 @@ export class ProcessServiceFactory implements IProcessServiceFactory { @inject(ICustomEnvironmentVariablesProvider) private readonly envVarsService: ICustomEnvironmentVariablesProvider ) {} - @traceDecoratorVerbose('Create ProcessService', TraceOptions.BeforeCall | TraceOptions.Arguments) + @debugDecorator('Create ProcessService', TraceOptions.BeforeCall | TraceOptions.Arguments) public async create(resource: Resource, cancelToken?: CancellationToken): Promise { // This should never happen, but if it does ensure we never run code accidentally in untrusted workspaces. if (!workspace.isTrusted) { diff --git a/src/platform/common/providerBasedQuickPick.ts b/src/platform/common/providerBasedQuickPick.ts index dc7c8718d8c..b5c191393f1 100644 --- a/src/platform/common/providerBasedQuickPick.ts +++ b/src/platform/common/providerBasedQuickPick.ts @@ -21,7 +21,7 @@ import { noop } from './utils/misc'; import { IDisposable } from './types'; import { dispose } from './utils/lifecycle'; import { DisposableBase } from './utils/lifecycle'; -import { traceError } from '../logging'; +import { logger } from '../logging'; abstract class BaseQuickPickItem implements QuickPickItem { label: string; @@ -194,7 +194,7 @@ export class BaseProviderBasedQuickPick extends Dispos this.updateQuickPickItems(quickPick, provider); }) - .catch((ex) => traceError(`Failed to get quick pick items for ${quickPick.title}`, ex)); + .catch((ex) => logger.error(`Failed to get quick pick items for ${quickPick.title}`, ex)); disposables.forEach((d) => this._register(d)); return { quickPick, disposables }; diff --git a/src/platform/common/utils/decorators.ts b/src/platform/common/utils/decorators.ts index 8a6369f31b2..cb5d15fa996 100644 --- a/src/platform/common/utils/decorators.ts +++ b/src/platform/common/utils/decorators.ts @@ -6,7 +6,7 @@ import { isTestExecution } from '../constants'; import { DataWithExpiry, getCacheKeyFromFunctionArgs, getGlobalCacheStore } from './cacheUtils'; import { noop } from './misc'; -import { traceError, traceVerbose, type TraceInfo } from '../../logging'; +import { logger, type TraceInfo } from '../../logging'; import { StopWatch } from './stopWatch'; import { isPromise } from './async'; @@ -28,7 +28,7 @@ export function cache(expiryDurationMs: number) { const key = getCacheKeyFromFunctionArgs(keyPrefix, args); const cachedItem = cacheStoreForMethods.get(key); if (cachedItem && !cachedItem.expired) { - traceVerbose(`Cached data exists ${key}`); + logger.debug(`Cached data exists ${key}`); return Promise.resolve(cachedItem.data); } const promise = originalMethod.apply(this, args) as Promise; @@ -64,14 +64,14 @@ export function swallowExceptions(scopeName?: string) { if (isTestExecution()) { return; } - traceError(errorMessage, error); + logger.error(errorMessage, error); }); } } catch (error) { if (isTestExecution()) { return; } - traceError(errorMessage, error); + logger.error(errorMessage, error); } }; }; diff --git a/src/platform/common/variables/customEnvironmentVariablesProvider.node.ts b/src/platform/common/variables/customEnvironmentVariablesProvider.node.ts index 04dbe60afe7..7b056477ed3 100644 --- a/src/platform/common/variables/customEnvironmentVariablesProvider.node.ts +++ b/src/platform/common/variables/customEnvironmentVariablesProvider.node.ts @@ -9,7 +9,7 @@ import { sendFileCreationTelemetry } from '../../telemetry/envFileTelemetry.node import { IDisposableRegistry, Resource } from '../types'; import { InMemoryCache } from '../utils/cacheUtils'; import { EnvironmentVariables, ICustomEnvironmentVariablesProvider, IEnvironmentVariablesService } from './types'; -import { traceDecoratorVerbose, traceError, traceInfoIfCI, traceVerbose } from '../../logging'; +import { debugDecorator, logger } from '../../logging'; import { dispose } from '../utils/lifecycle'; import { IPythonApiProvider, IPythonExtensionChecker } from '../../api/types'; import { noop } from '../utils/misc'; @@ -44,7 +44,7 @@ export class CustomEnvironmentVariablesProvider implements ICustomEnvironmentVar dispose(this.disposables); } - @traceDecoratorVerbose('Get Custom Env Variables', TraceOptions.Arguments) + @debugDecorator('Get Custom Env Variables', TraceOptions.Arguments) public async getEnvironmentVariables( resource: Resource, purpose: 'RunPythonCode' | 'RunNonPythonCode', @@ -66,7 +66,7 @@ export class CustomEnvironmentVariablesProvider implements ICustomEnvironmentVar ); if (cacheStoreIndexedByWorkspaceFolder.hasData && cacheStoreIndexedByWorkspaceFolder.data) { - traceVerbose(`Cached data exists getEnvironmentVariables, ${resource ? resource.fsPath : ''}`); + logger.debug(`Cached data exists getEnvironmentVariables, ${resource ? resource.fsPath : ''}`); return cacheStoreIndexedByWorkspaceFolder.data!; } const promise = this._getEnvironmentVariables(resource, purpose, token); @@ -91,7 +91,7 @@ export class CustomEnvironmentVariablesProvider implements ICustomEnvironmentVar : undefined; const workspaceFolderUri = this.getWorkspaceFolderUri(resource); if (!workspaceFolderUri) { - traceInfoIfCI(`No workspace folder found for ${resource ? resource.fsPath : ''}`); + logger.ci(`No workspace folder found for ${resource ? resource.fsPath : ''}`); return; } @@ -102,7 +102,7 @@ export class CustomEnvironmentVariablesProvider implements ICustomEnvironmentVar this.pythonEnvVarChangeEventHooked = true; api.environments.onDidEnvironmentVariablesChange( (e) => { - traceVerbose(`Python env vars changed ${e.resource?.uri?.path}`); + logger.debug(`Python env vars changed ${e.resource?.uri?.path}`); this.onEnvironmentFileChanged(e.resource?.uri); this.changeEventEmitter.fire(e.resource?.uri); }, @@ -120,7 +120,7 @@ export class CustomEnvironmentVariablesProvider implements ICustomEnvironmentVar ); if (cacheStoreIndexedByWorkspaceFolder.hasData) { - traceVerbose( + logger.debug( `Cached custom vars data exists getCustomEnvironmentVariables, ${ resource ? resource.fsPath : '' }` @@ -159,7 +159,7 @@ export class CustomEnvironmentVariablesProvider implements ICustomEnvironmentVar envFileWatcher.onDidCreate(() => this.onEnvironmentFileCreated(workspaceFolderUri), this, this.disposables); envFileWatcher.onDidDelete(() => this.onEnvironmentFileChanged(workspaceFolderUri), this, this.disposables); } else { - traceError('Failed to create file watcher for environment file'); + logger.error('Failed to create file watcher for environment file'); } } private getEnvFile(workspaceFolderUri: Uri) { diff --git a/src/platform/common/variables/customEnvironmentVariablesProvider.node.unit.test.ts b/src/platform/common/variables/customEnvironmentVariablesProvider.node.unit.test.ts index 0de9ce5a415..69417dcdcf1 100644 --- a/src/platform/common/variables/customEnvironmentVariablesProvider.node.unit.test.ts +++ b/src/platform/common/variables/customEnvironmentVariablesProvider.node.unit.test.ts @@ -11,7 +11,7 @@ import { IEnvironmentVariablesService } from './types'; import * as fs from 'fs-extra'; import dedent from 'dedent'; import { IPythonApiProvider, IPythonExtensionChecker } from '../../api/types'; -import { traceInfo } from '../../logging'; +import { logger } from '../../logging'; import { anything, instance, mock, when } from 'ts-mockito'; import { clearCache } from '../utils/cacheUtils'; import { EnvironmentVariablesService } from './environment.node'; @@ -43,7 +43,7 @@ suite('Custom Environment Variables Provider', () => { const workspaceUri = Uri.joinPath(Uri.file(EXTENSION_ROOT_DIR_FOR_TESTS), 'src', 'test', 'datascience'); const workspaceFolder = { index: 0, name: 'workspace', uri: workspaceUri }; setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); clearCache(); envVarsService = new EnvironmentVariablesService(new FileSystem()); pythonExtChecker = mock(); @@ -73,14 +73,14 @@ suite('Custom Environment Variables Provider', () => { ).thenReturn(instance(fsWatcher)); }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); disposables = dispose(disposables); if (fs.existsSync(customPythonEnvFile.fsPath)) { fs.unlinkSync(customPythonEnvFile.fsPath); } fs.writeFileSync(envFile.fsPath, contentsOfOldEnvFile); sinon.restore(); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); function createProvider(cacheDuration?: number) { @@ -98,7 +98,7 @@ suite('Custom Environment Variables Provider', () => { VSCODE_JUPYTER_ENV_TEST_VAR1=FOO VSCODE_JUPYTER_ENV_TEST_VAR2=BAR `; - traceInfo('Write to env file', envFile.fsPath); + logger.info('Write to env file', envFile.fsPath); fs.writeFileSync(envFile.fsPath, envVars); createProvider(); const vars = await customEnvVarsProvider.getCustomEnvironmentVariables(undefined, 'RunNonPythonCode'); @@ -123,7 +123,7 @@ suite('Custom Environment Variables Provider', () => { VSCODE_JUPYTER_ENV_TEST_VAR1=FOO VSCODE_JUPYTER_ENV_TEST_VAR2=BAR `; - traceInfo('Write to env file1', envFile.fsPath); + logger.info('Write to env file1', envFile.fsPath); fs.writeFileSync(envFile.fsPath, envVars); createProvider(); let vars = await customEnvVarsProvider.getCustomEnvironmentVariables(undefined, 'RunNonPythonCode'); @@ -143,7 +143,7 @@ suite('Custom Environment Variables Provider', () => { VSCODE_JUPYTER_ENV_TEST_VAR1=FOO2 VSCODE_JUPYTER_ENV_TEST_VAR2=BAR2 `; - traceInfo('Write to env file2', envFile.fsPath); + logger.info('Write to env file2', envFile.fsPath); fs.writeFileSync(envFile.fsPath, envVars); onFSEvent.fire(envFile); @@ -158,7 +158,7 @@ suite('Custom Environment Variables Provider', () => { }); }); test('Detects creation of the .env file', async () => { - traceInfo('Delete to env file', envFile.fsPath); + logger.info('Delete to env file', envFile.fsPath); fs.unlinkSync(envFile.fsPath); createProvider(); let vars = await customEnvVarsProvider.getCustomEnvironmentVariables(undefined, 'RunNonPythonCode'); @@ -174,7 +174,7 @@ suite('Custom Environment Variables Provider', () => { VSCODE_JUPYTER_ENV_TEST_VAR1=FOO2 VSCODE_JUPYTER_ENV_TEST_VAR2=BAR2 `; - traceInfo('Create env file', envFile.fsPath); + logger.info('Create env file', envFile.fsPath); fs.writeFileSync(envFile.fsPath, envVars); onFSEvent.fire(envFile); @@ -193,13 +193,13 @@ suite('Custom Environment Variables Provider', () => { VSCODE_JUPYTER_ENV_TEST_VAR1=FOO VSCODE_JUPYTER_ENV_TEST_VAR2=BAR `; - traceInfo('Write to env file', envFile.fsPath); + logger.info('Write to env file', envFile.fsPath); fs.writeFileSync(envFile.fsPath, envVars); const pythonEnvVars = dedent` VSCODE_JUPYTER_ENV_TEST_VAR1=PYTHON_FOO VSCODE_JUPYTER_ENV_TEST_VAR2=PYTHON_BAR `; - traceInfo('Write to python env file', customPythonEnvFile.fsPath); + logger.info('Write to python env file', customPythonEnvFile.fsPath); fs.writeFileSync(customPythonEnvFile.fsPath, pythonEnvVars); const environments = mock(); when(environments.getEnvironmentVariables(anything())).thenReturn({ diff --git a/src/platform/common/variables/environment.node.ts b/src/platform/common/variables/environment.node.ts index ddc779b2d3b..01be5b3ec9d 100644 --- a/src/platform/common/variables/environment.node.ts +++ b/src/platform/common/variables/environment.node.ts @@ -6,7 +6,7 @@ import { inject, injectable } from 'inversify'; import * as path from '../../vscode-path/path'; import { sendTelemetryEvent } from '../../../telemetry'; import { EventName } from '../../telemetry/constants'; -import { traceError } from '../../logging'; +import { logger } from '../../logging'; import { isFileNotFoundError } from '../platform/errors'; import { EnvironmentVariables, IEnvironmentVariablesService } from './types'; import { Uri } from 'vscode'; @@ -30,7 +30,7 @@ export class EnvironmentVariablesService implements IEnvironmentVariablesService return parseEnvFile(await this.fs.readFile(Uri.file(filePath)), baseVars); } catch (ex) { if (!isFileNotFoundError(ex)) { - traceError(`Failed to parse env file ${filePath}`, ex); + logger.error(`Failed to parse env file ${filePath}`, ex); } } } diff --git a/src/platform/interpreter/condaService.node.ts b/src/platform/interpreter/condaService.node.ts index d01cde90907..2f80ccabff6 100644 --- a/src/platform/interpreter/condaService.node.ts +++ b/src/platform/interpreter/condaService.node.ts @@ -5,7 +5,7 @@ import { inject, injectable, named } from 'inversify'; import { SemVer } from 'semver'; import { Memento, Uri } from 'vscode'; import { IPythonApiProvider } from '../api/types'; -import { traceVerbose } from '../logging'; +import { logger } from '../logging'; import { IFileSystem } from '../common/platform/types'; import { GLOBAL_MEMENTO, IMemento } from '../common/types'; import { createDeferredFromPromise } from '../common/utils/async'; @@ -83,7 +83,7 @@ export class CondaService { .then((api) => (api.getCondaFile ? api.getCondaFile() : undefined)); latestInfo .then((file) => { - traceVerbose(`Conda file is ${file}`); + logger.debug(`Conda file is ${file}`); this._file = file ? Uri.file(file) : undefined; this.updateCache().catch(noop); }) diff --git a/src/platform/interpreter/environmentActivationService.node.ts b/src/platform/interpreter/environmentActivationService.node.ts index 6b1b4d2cd14..4a3d02c6c26 100644 --- a/src/platform/interpreter/environmentActivationService.node.ts +++ b/src/platform/interpreter/environmentActivationService.node.ts @@ -16,7 +16,7 @@ import { IInterpreterService } from './contracts'; import { DataScience } from '../common/utils/localize'; import { KernelProgressReporter } from '../progress/kernelProgressReporter'; import { Telemetry } from '../common/constants'; -import { ignoreLogging, logValue, traceDecoratorVerbose, traceError, traceVerbose, traceWarning } from '../logging'; +import { ignoreLogging, logValue, debugDecorator, logger } from '../logging'; import { TraceOptions } from '../logging/types'; import { GlobalPythonExecutablePathService } from './globalPythonExePathService.node'; import { noop } from '../common/utils/misc'; @@ -71,7 +71,7 @@ export class EnvironmentActivationService implements IEnvironmentActivationServi ): Promise { const env = await this.interpreterService.resolveEnvironment(interpreterId); if (!env) { - traceWarning(`Failed to resolve environment for ${interpreterId}`); + logger.warn(`Failed to resolve environment for ${interpreterId}`); return; } const key = `${resource?.toString() || ''}${interpreterId}`; @@ -90,7 +90,7 @@ export class EnvironmentActivationService implements IEnvironmentActivationServi } return raceCancellation(token, promise); } - @traceDecoratorVerbose('Getting activated env variables', TraceOptions.Arguments) + @debugDecorator('Getting activated env variables', TraceOptions.Arguments) private async getActivatedEnvironmentVariablesImpl( resource: Resource, @logValue('id') environment: Environment, @@ -108,7 +108,7 @@ export class EnvironmentActivationService implements IEnvironmentActivationServi return env; }) .catch((ex) => { - traceError( + logger.error( `Failed to get env vars with python ${getDisplayPath(environment.id)} in ${ stopWatch.elapsedTime }ms`, @@ -166,7 +166,7 @@ export class EnvironmentActivationService implements IEnvironmentActivationServi let env = await this.apiProvider.getApi().then((api) => api.getActivatedEnvironmentVariables(resource, environment, false).catch((ex) => { - traceError( + logger.error( `Failed to get activated env variables from Python Extension for ${getDisplayPath( environment.path )}`, @@ -193,7 +193,7 @@ export class EnvironmentActivationService implements IEnvironmentActivationServi ); if (env) { - traceVerbose( + logger.debug( `Got env vars from Python Ext in ${stopWatch.elapsedTime}ms for ${getDisplayPath( environment.path )}, with env var count ${Object.keys(env || {}).length}.` @@ -201,12 +201,12 @@ export class EnvironmentActivationService implements IEnvironmentActivationServi } else if (envType === EnvironmentType.Conda) { // We must get activated env variables for Conda env, if not running stuff against conda will not work. // Hence we must log these as errors (so we can see them in jupyter logs). - traceError( + logger.error( `Failed to get activated conda env vars for ${getDisplayPath(environment.path)} in ${stopWatch.elapsedTime}ms` ); } else { - traceWarning( + logger.warn( `Failed to get activated env vars for ${getDisplayPath(environment.path)} in ${stopWatch.elapsedTime}ms` ); } @@ -222,7 +222,7 @@ export class EnvironmentActivationService implements IEnvironmentActivationServi if (sysPrefix) { env.CONDA_PREFIX = sysPrefix; } else { - traceWarning( + logger.warn( `Failed to get the SysPrefix for the Conda Environment ${getDisplayPath(environment.path)}}` ); } @@ -252,7 +252,7 @@ export class EnvironmentActivationService implements IEnvironmentActivationServi // First value in PATH is expected to be the directory of python executable. // Second value in PATH is expected to be the site packages directory. if (executablesPath && pathValues[1] !== executablesPath.fsPath) { - traceVerbose( + logger.debug( `Prepend PATH with user site path for ${getDisplayPath(environment.path)}, user site ${ executablesPath.fsPath }` @@ -262,7 +262,7 @@ export class EnvironmentActivationService implements IEnvironmentActivationServi } else if (isCondaEnvironmentWithoutPython(environment)) { // } else { - traceError( + logger.error( `Unable to determine site packages path for python ${getDisplayPath( environment.path )} (${getEnvironmentType(environment)})` @@ -284,7 +284,7 @@ export class EnvironmentActivationService implements IEnvironmentActivationServi // Also applies to `!java` where java could be an executable in the conda bin directory. // Also required for conda environments that do not have Python installed (in the conda env). if (environment.executable.uri) { - traceVerbose(`Prepend PATH with python bin for ${getDisplayPath(environment.path)}`); + logger.debug(`Prepend PATH with python bin for ${getDisplayPath(environment.path)}`); this.envVarsService.prependPath(env, path.dirname(environment.executable.uri.fsPath)); } diff --git a/src/platform/interpreter/filter/completionProvider.node.ts b/src/platform/interpreter/filter/completionProvider.node.ts index 938cae55ca3..b477bce379e 100644 --- a/src/platform/interpreter/filter/completionProvider.node.ts +++ b/src/platform/interpreter/filter/completionProvider.node.ts @@ -11,7 +11,7 @@ import { IPythonExtensionChecker } from '../../api/types'; import { getDisplayPath } from '../../common/platform/fs-paths'; import { getCachedEnvironments, getPythonEnvDisplayName } from '../helpers'; import { isPythonEnvInListOfHiddenEnvs } from './filterService'; -import { traceWarning } from '../../logging'; +import { logger } from '../../logging'; @injectable() export class PythonEnvFilterCompletionProvider implements CompletionItemProvider, IExtensionSyncActivationService { @@ -82,7 +82,7 @@ export class PythonEnvFilterCompletionProvider implements CompletionItemProvider const items = getNodeValue(settingsNode) as string[]; return Array.isArray(items) ? items : []; } catch (ex) { - traceWarning(`Failed to provide completions for python env filter`, ex); + logger.warn(`Failed to provide completions for python env filter`, ex); return []; } } diff --git a/src/platform/interpreter/filter/filterService.ts b/src/platform/interpreter/filter/filterService.ts index b21d9ca787c..b10da0532d5 100644 --- a/src/platform/interpreter/filter/filterService.ts +++ b/src/platform/interpreter/filter/filterService.ts @@ -8,7 +8,7 @@ import { IDisposable, IDisposableRegistry } from '../../common/types'; import { sendTelemetryEvent } from '../../../telemetry'; import { Telemetry, isWebExtension } from '../../common/constants'; import { getDisplayPath } from '../../common/platform/fs-paths'; -import { traceVerbose } from '../../logging'; +import { logger } from '../../logging'; import { Environment } from '@vscode/python-extension'; /** @@ -46,7 +46,7 @@ export class PythonEnvironmentFilter implements IDisposable { const interpreterUri = 'uri' in interpreter ? interpreter.uri : interpreter.executable.uri; if (hidden) { sendTelemetryEvent(Telemetry.JupyterKernelHiddenViaFilter); - traceVerbose(`Python Env hidden via filter: ${getDisplayPath(interpreterUri)}`); + logger.debug(`Python Env hidden via filter: ${getDisplayPath(interpreterUri)}`); } return hidden; } diff --git a/src/platform/interpreter/globalPythonExePathService.node.ts b/src/platform/interpreter/globalPythonExePathService.node.ts index 7044b5037af..0f9fc4d6305 100644 --- a/src/platform/interpreter/globalPythonExePathService.node.ts +++ b/src/platform/interpreter/globalPythonExePathService.node.ts @@ -8,7 +8,7 @@ import { EnvironmentType } from '../pythonEnvironments/info'; import { IFileSystem, IPlatformService } from '../common/platform/types'; import { swallowExceptions } from '../common/utils/decorators'; import { IProcessServiceFactory } from '../common/process/types.node'; -import { traceVerbose } from '../logging'; +import { logger } from '../logging'; import { getDisplayPath } from '../common/platform/fs-paths'; import { Environment } from '@vscode/python-extension'; import { getEnvironmentType } from './helpers'; @@ -93,7 +93,7 @@ export class GlobalPythonExecutablePathService { `USER_SITE ${sitePath.fsPath} dir does not exist for the interpreter ${getDisplayPath(executable)}` ); } - traceVerbose(`USER_SITE for ${getDisplayPath(executable)} is ${sitePath.fsPath}`); + logger.debug(`USER_SITE for ${getDisplayPath(executable)} is ${sitePath.fsPath}`); return sitePath; } else { throw new Error(`USER_SITE not found for the interpreter ${getDisplayPath(executable)}. Stdout: ${stdout}`); diff --git a/src/platform/interpreter/helpers.ts b/src/platform/interpreter/helpers.ts index 9122f28e86a..1117ed06467 100644 --- a/src/platform/interpreter/helpers.ts +++ b/src/platform/interpreter/helpers.ts @@ -5,7 +5,7 @@ import { EnvironmentType, PythonEnvironment } from '../pythonEnvironments/info'; import { getTelemetrySafeVersion } from '../telemetry/helpers'; import { basename } from '../../platform/vscode-path/resources'; import { Environment, KnownEnvironmentTools, KnownEnvironmentTypes, PythonExtension } from '@vscode/python-extension'; -import { traceWarning } from '../logging'; +import { logger } from '../logging'; import { getDisplayPath } from '../common/platform/fs-paths'; import { Uri } from 'vscode'; import { getOSType, OSType } from '../common/utils/platform'; @@ -164,7 +164,7 @@ export async function getSysPrefix(interpreter?: { id: string }) { const api = await PythonExtension.api(); const sysPrefix = await api.environments.resolveEnvironment(interpreter.id).then((i) => i?.executable?.sysPrefix); if (!sysPrefix) { - traceWarning(`Unable to find sysPrefix for interpreter ${getDisplayPath(interpreter.id)}`); + logger.warn(`Unable to find sysPrefix for interpreter ${getDisplayPath(interpreter.id)}`); } return sysPrefix; } @@ -193,7 +193,7 @@ export async function getVersion(interpreter?: { id?: string }, ignoreCache = fa const api = await PythonExtension.api(); const info = await api.environments.resolveEnvironment(interpreter.id); if (!info?.version) { - traceWarning(`Unable to find Version for interpreter ${getDisplayPath(interpreter.id)}`); + logger.warn(`Unable to find Version for interpreter ${getDisplayPath(interpreter.id)}`); } return info?.version; } @@ -229,7 +229,7 @@ export function resolvedPythonEnvToJupyterEnv(env?: Environment): PythonEnvironm ? Uri.joinPath(env.environment?.folderUri || Uri.file(env.path), 'python.exe') : Uri.joinPath(env.environment?.folderUri || Uri.file(env.path), 'bin', 'python'); } else { - traceWarning(`Python environment ${getDisplayPath(env.id)} excluded as Uri is undefined`); + logger.warn(`Python environment ${getDisplayPath(env.id)} excluded as Uri is undefined`); return; } } else { diff --git a/src/platform/interpreter/installer/moduleInstaller.node.ts b/src/platform/interpreter/installer/moduleInstaller.node.ts index 733dde660de..bc7ed7785a9 100644 --- a/src/platform/interpreter/installer/moduleInstaller.node.ts +++ b/src/platform/interpreter/installer/moduleInstaller.node.ts @@ -9,7 +9,7 @@ import { ProgressOptions, window } from 'vscode'; -import { traceVerbose } from '../../logging'; +import { logger } from '../../logging'; import { IProcessServiceFactory, ObservableExecutionResult } from '../../common/process/types.node'; import { createDeferred } from '../../common/utils/async'; import { Products } from '../../common/utils/localize'; @@ -94,7 +94,7 @@ export abstract class ModuleInstaller implements IModuleInstaller { } try { const results = await proc.shellExec(args.args.join(' '), { cwd: args.cwd }); - traceVerbose(results.stdout); + logger.debug(results.stdout); deferred.resolve(); } catch (ex) { deferred.reject(ex); @@ -139,7 +139,7 @@ export abstract class ModuleInstaller implements IModuleInstaller { const message = trimmedOutput.length > 28 ? `${trimmedOutput.substring(0, 28)}${suffix}` : trimmedOutput; progress.report({ message }); - traceVerbose(output.out); + logger.debug(output.out); if (output.source === 'stderr') { // https://github.com/microsoft/vscode-jupyter/issues/12703 // Sometimes on windows we get an error that says "ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory:" diff --git a/src/platform/interpreter/installer/pipenv.node.ts b/src/platform/interpreter/installer/pipenv.node.ts index 462b47c2439..a003299ea2c 100644 --- a/src/platform/interpreter/installer/pipenv.node.ts +++ b/src/platform/interpreter/installer/pipenv.node.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import * as path from '../../vscode-path/path'; -import { traceError } from '../../logging'; +import { logger } from '../../logging'; import { getEnvironmentVariable } from '../../common/utils/platform.node'; import { pathExists, readFile } from '../../common/platform/fileUtils.node'; import { Uri } from 'vscode'; @@ -18,7 +18,7 @@ function getSearchHeight() { const maxDepth = parseInt(maxDepthStr, 10); // eslint-disable-next-line no-restricted-globals if (isNaN(maxDepth)) { - traceError(`PIPENV_MAX_DEPTH is incorrectly set. Converting value '${maxDepthStr}' to number results in NaN`); + logger.error(`PIPENV_MAX_DEPTH is incorrectly set. Converting value '${maxDepthStr}' to number results in NaN`); return 1; } return maxDepth; @@ -65,7 +65,7 @@ async function getProjectDir(envFolder: string): Promise { } const projectDir = await readFile(dotProjectFile); if (!(await pathExists(projectDir))) { - traceError( + logger.error( `The .project file inside environment folder: ${envFolder} doesn't contain a valid path to the project` ); return undefined; diff --git a/src/platform/interpreter/installer/poetry.node.ts b/src/platform/interpreter/installer/poetry.node.ts index 98aa0da56e2..18dd0571c71 100644 --- a/src/platform/interpreter/installer/poetry.node.ts +++ b/src/platform/interpreter/installer/poetry.node.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import * as path from '../../vscode-path/path'; -import { traceVerbose, traceError } from '../../logging'; +import { logger } from '../../logging'; import { cache } from '../../common/utils/decorators'; import { getOSType, getUserHomeDir, OSType } from '../../common/utils/platform.node'; import { StopWatch } from '../../common/utils/stopWatch'; @@ -141,7 +141,7 @@ export class Poetry { // First thing this method awaits on should be poetry command execution, hence perform all operations // before that synchronously. - traceVerbose(`Getting poetry for cwd ${cwd}`); + logger.debug(`Getting poetry for cwd ${cwd}`); // Produce a list of candidate binaries to be probed by exec'ing them. function* getCandidates() { const customPoetryPath = getPythonSetting('poetryPath'); @@ -162,18 +162,18 @@ export class Poetry { // Probe the candidates, and pick the first one that exists and does what we need. for (const poetryPath of getCandidates()) { - traceVerbose(`Probing poetry binary for ${cwd}: ${poetryPath}`); + logger.debug(`Probing poetry binary for ${cwd}: ${poetryPath}`); const poetry = new Poetry(poetryPath, cwd); const virtualenvs = await poetry.getEnvList(); if (virtualenvs !== undefined) { - traceVerbose(`Found poetry via filesystem probing for ${cwd}: ${poetryPath}`); + logger.debug(`Found poetry via filesystem probing for ${cwd}: ${poetryPath}`); return poetry; } - traceVerbose(`Failed to find poetry for ${cwd}: ${poetryPath}`); + logger.debug(`Failed to find poetry for ${cwd}: ${poetryPath}`); } // Didn't find anything. - traceVerbose(`No poetry binary found for ${cwd}`); + logger.debug(`No poetry binary found for ${cwd}`); return undefined; } @@ -285,13 +285,13 @@ export class Poetry { timeout: POETRY_TIMEOUT }).catch((ex) => { if (logVerbose) { - traceVerbose(ex); + logger.debug(ex); } else { - traceError(ex); + logger.error(ex); } return undefined; }); - traceVerbose(`Time taken to run ${command} in ms`, stopWatch.elapsedTime); + logger.debug(`Time taken to run ${command} in ms`, stopWatch.elapsedTime); return result; } } diff --git a/src/platform/interpreter/installer/productInstaller.node.ts b/src/platform/interpreter/installer/productInstaller.node.ts index a3a3ff901e3..cec9855516a 100644 --- a/src/platform/interpreter/installer/productInstaller.node.ts +++ b/src/platform/interpreter/installer/productInstaller.node.ts @@ -14,9 +14,9 @@ import { Product, ProductType } from './types'; -import { logValue, traceDecoratorVerbose } from '../../logging'; +import { logValue, debugDecorator } from '../../logging'; import { PythonEnvironment } from '../../pythonEnvironments/info'; -import { traceError } from '../../logging'; +import { logger } from '../../logging'; import { IProcessServiceFactory } from '../../common/process/types.node'; import { IConfigurationService, @@ -50,7 +50,7 @@ export async function isModulePresentInEnvironment(memento: Memento, product: Pr .getPackageVersion(interpreter, packageName) .then((version) => (typeof version === 'string' ? 'found' : 'notfound')) .catch((ex) => { - traceError('Failed to get interpreter package version', ex); + logger.error('Failed to get interpreter package version', ex); return undefined; }) : Promise.resolve(undefined); @@ -61,7 +61,7 @@ export async function isModulePresentInEnvironment(memento: Memento, product: Pr return version === 'found'; } } catch (ex) { - traceError(`Failed to check if package exists ${ProductNames.get(product)}`); + logger.error(`Failed to check if package exists ${ProductNames.get(product)}`); } } @@ -115,7 +115,7 @@ export class DataScienceInstaller { }); } - @traceDecoratorVerbose('Checking if product is installed') + @debugDecorator('Checking if product is installed') public async isInstalled( product: Product, @logValue('path') interpreter: PythonEnvironment | Environment diff --git a/src/platform/interpreter/internal/python.node.ts b/src/platform/interpreter/internal/python.node.ts index ac5f9d284ad..0c610d3af52 100644 --- a/src/platform/interpreter/internal/python.node.ts +++ b/src/platform/interpreter/internal/python.node.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { traceVerbose } from '../../logging'; +import { logger } from '../../logging'; // "python" contains functions corresponding to the various ways that // the extension invokes a Python executable internally. Each function @@ -39,7 +39,7 @@ export function isModuleInstalled(name: string): [string[], (out: string) => boo if (out.includes('6af208d0-cb9c-427f-b937-ff563e17efdf')) { return true; } else { - traceVerbose(`Module ${name} is not installed. Output ${out}`); + logger.debug(`Module ${name} is not installed. Output ${out}`); return false; } } diff --git a/src/platform/interpreter/interpreterPackages.node.ts b/src/platform/interpreter/interpreterPackages.node.ts index a90008197a9..0a45224c771 100644 --- a/src/platform/interpreter/interpreterPackages.node.ts +++ b/src/platform/interpreter/interpreterPackages.node.ts @@ -10,7 +10,7 @@ import { IInterpreterService } from './contracts'; import { PythonEnvironment } from '../pythonEnvironments/info'; import { getComparisonKey } from '../vscode-path/resources'; import { getTelemetrySafeHashedString, getTelemetrySafeVersion } from '../telemetry/helpers'; -import { traceError, traceWarning } from '../logging'; +import { logger } from '../logging'; import { getDisplayPath } from '../common/platform/fs-paths.node'; import { IInterpreterPackages } from './types'; import { IPythonExecutionFactory } from './types.node'; @@ -111,7 +111,7 @@ export class InterpreterPackages implements IInterpreterPackages { if (this.interpreterPackages.get(workspaceKey) === promise) { this.interpreterPackages.delete(workspaceKey)!; } - traceWarning(`Failed to get list of installed packages for ${workspaceKey}`, ex); + logger.warn(`Failed to get list of installed packages for ${workspaceKey}`, ex); }); } return this.interpreterPackages.get(workspaceKey)!.then((items) => Array.from(items)); @@ -129,7 +129,7 @@ export class InterpreterPackages implements IInterpreterPackages { const modules = JSON.parse(modulesOutput.stdout.split(separator)[1].trim()) as string[]; return new Set(modules.concat(modules.map((item) => item.toLowerCase()))); } else { - traceError( + logger.error( `Failed to get list of installed packages for ${getDisplayPath(interpreter.uri)}`, modulesOutput.stderr ); diff --git a/src/platform/interpreter/pythonEnvironment.node.ts b/src/platform/interpreter/pythonEnvironment.node.ts index 65b9f9c7055..5358479dcd2 100644 --- a/src/platform/interpreter/pythonEnvironment.node.ts +++ b/src/platform/interpreter/pythonEnvironment.node.ts @@ -9,7 +9,7 @@ import { SemVer } from 'semver'; import { getFilePath } from '../common/platform/fs-paths'; import { Uri } from 'vscode'; import { IFileSystem } from '../common/platform/types'; -import { traceWarning } from '../logging'; +import { logger } from '../logging'; import { Environment } from '@vscode/python-extension'; class PythonEnvironment { private readonly executable: Uri; @@ -63,7 +63,7 @@ class PythonEnvironment { const output = await this.deps.exec(info.command, info.args, { throwOnStdErr: false }); return parse(output.stdout); } catch (ex) { - traceWarning(`Module ${moduleName} not installed in environment ${this.pythonEnvId}`, ex); + logger.warn(`Module ${moduleName} not installed in environment ${this.pythonEnvId}`, ex); return false; } } diff --git a/src/platform/interpreter/pythonEnvironmentQuickPickProvider.node.ts b/src/platform/interpreter/pythonEnvironmentQuickPickProvider.node.ts index 72f9b8ef5cb..2c6352fbc4b 100644 --- a/src/platform/interpreter/pythonEnvironmentQuickPickProvider.node.ts +++ b/src/platform/interpreter/pythonEnvironmentQuickPickProvider.node.ts @@ -9,7 +9,7 @@ import { IExtensionSyncActivationService } from '../activation/types'; import { IDisposable, IDisposableRegistry } from '../common/types'; import { PromiseMonitor } from '../common/utils/promises'; import { IPythonApiProvider, IPythonExtensionChecker } from '../api/types'; -import { traceError } from '../logging'; +import { logger } from '../logging'; import { DataScience } from '../common/utils/localize'; import { noop } from '../common/utils/misc'; import { dispose } from '../common/utils/lifecycle'; @@ -70,7 +70,7 @@ export class PythonEnvironmentQuickPickItemProvider this._onDidChange.fire(); api.environments.onDidChangeEnvironments(() => this._onDidChange.fire(), this, this.disposables); }) - .catch((ex) => traceError('Failed to get python api', ex)); + .catch((ex) => logger.error('Failed to get python api', ex)); }; if (extensionChecker.isPythonExtensionInstalled) { initializeApi(); diff --git a/src/platform/ioc/container.ts b/src/platform/ioc/container.ts index 71fe6a482eb..17f3b1bbe91 100644 --- a/src/platform/ioc/container.ts +++ b/src/platform/ioc/container.ts @@ -3,7 +3,7 @@ import { EventEmitter } from 'events'; import { Container, decorate, injectable, interfaces } from 'inversify'; -import { traceWarning } from '../logging'; +import { logger } from '../logging'; import { Abstract, IServiceContainer, Newable } from './types'; // This needs to be done once, hence placed in a common location. @@ -13,7 +13,7 @@ import { Abstract, IServiceContainer, Newable } from './types'; try { decorate(injectable(), EventEmitter); } catch (ex) { - traceWarning('Failed to decorate EventEmitter for DI (possibly already decorated by another Extension)', ex); + logger.warn('Failed to decorate EventEmitter for DI (possibly already decorated by another Extension)', ex); } /** diff --git a/src/platform/logging/consoleLogger.ts b/src/platform/logging/consoleLogger.ts index ecdee7b0ae1..60ac077987d 100644 --- a/src/platform/logging/consoleLogger.ts +++ b/src/platform/logging/consoleLogger.ts @@ -26,10 +26,14 @@ export class ConsoleLogger implements ILogger { console.info(formatMessage('info', `${this.prefix || ''} ${message}`, ...data)); } - public verbose(message: string, ...data: Arguments): void { + public debug(message: string, ...data: Arguments): void { console.log(formatMessage('debug', `${this.prefix || ''} ${message}`, ...data)); } public trace(message: string, ...data: Arguments): void { console.trace(formatMessage('trace', `${this.prefix || ''} ${message}`, ...data)); } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + public ci(_message: any, ..._data: Arguments): void { + // + } } diff --git a/src/platform/logging/index.ts b/src/platform/logging/index.ts index 8ebb0829298..9315b6f76bb 100644 --- a/src/platform/logging/index.ts +++ b/src/platform/logging/index.ts @@ -33,11 +33,18 @@ export type TraceInfo = let loggers: ILogger[] = []; let globalLoggingLevel: LogLevel = LogLevel.Info; export const logger: ILogger = { - error: (message: string, ...data: Arguments) => traceError(message, ...data), - warn: (message: string, ...data: Arguments) => traceWarning(message, ...data), - info: (message: string, ...data: Arguments) => traceInfo(message, ...data), - verbose: (message: string, ...data: Arguments) => traceVerbose(message, ...data), - trace: (message: string, ...data: Arguments) => traceTrace(message, ...data) + error: (message: string, ...data: Arguments) => logError(message, ...data), + warn: (message: string, ...data: Arguments) => logWarning(message, ...data), + info: (message: string, ...data: Arguments) => logInfo(message, ...data), + debug: (message: string, ...data: Arguments) => logDebug(message, ...data), + trace: (message: string, ...data: Arguments) => logTrace(message, ...data), + ci: (arg1: any, ...data: string[]) => { + if (data && Array.isArray(data)) { + logInfoIfCI(arg1, ...data); + } else { + logInfoIfCI(arg1); + } + } }; export function initializeLoggers(options: { @@ -179,38 +186,38 @@ function formatErrors(...args: Arguments) { .join('\n'); }); } -export function traceError(message: string, ...args: Arguments): void { +function logError(message: string, ...args: Arguments): void { if (globalLoggingLevel <= LogLevel.Error) { args = formatErrors(...args); loggers.forEach((l) => l.error(message, ...args)); } } -export function traceWarning(message: string, ...args: Arguments): void { +function logWarning(message: string, ...args: Arguments): void { if (globalLoggingLevel <= LogLevel.Warning) { args = formatErrors(...args); loggers.forEach((l) => l.warn(message, ...args)); } } -export function traceInfo(message: string, ...args: Arguments): void { +function logInfo(message: string, ...args: Arguments): void { if (globalLoggingLevel <= LogLevel.Info) { loggers.forEach((l) => l.info(message, ...args)); } } -export function traceVerbose(message: string, ...args: Arguments): void { +function logDebug(message: string, ...args: Arguments): void { if (globalLoggingLevel <= LogLevel.Debug) { - loggers.forEach((l) => l.verbose(message, ...args)); + loggers.forEach((l) => l.debug(message, ...args)); } } -export function traceTrace(message: string, ...args: Arguments): void { +function logTrace(message: string, ...args: Arguments): void { if (globalLoggingLevel <= LogLevel.Trace) { loggers.forEach((l) => l.trace(message, ...args)); } } -export function traceInfoIfCI(msg: () => [message: string, ...args: string[]] | string): void; -export function traceInfoIfCI(message: string, ...args: string[]): void; -export function traceInfoIfCI(arg1: any, ...args: Arguments): void { +function logInfoIfCI(msg: () => [message: string, ...args: string[]] | string): void; +function logInfoIfCI(message: string, ...args: string[]): void; +function logInfoIfCI(arg1: any, ...args: Arguments): void { if (isCI) { if (typeof arg1 === 'function') { const fn: () => string | [message: string, ...args: string[]] = arg1; @@ -223,25 +230,25 @@ export function traceInfoIfCI(arg1: any, ...args: Arguments): void { message = result.shift()!; rest = result; } - traceInfo(message, ...rest); + logger.info(message, ...rest); } else { - traceInfo(arg1, ...args); + logger.info(arg1, ...args); } } } /** Logging Decorators go here */ -export function traceDecoratorVerbose(message: string, opts: TraceOptions = DEFAULT_OPTS): TraceDecoratorType { +export function debugDecorator(message: string, opts: TraceOptions = DEFAULT_OPTS): TraceDecoratorType { return createTracingDecorator({ message, opts, level: LogLevel.Debug }); } -export function traceDecoratorError(message: string): TraceDecoratorType { +export function errorDecorator(message: string): TraceDecoratorType { return createTracingDecorator({ message, opts: DEFAULT_OPTS, level: LogLevel.Error }); } -export function traceDecoratorInfo(message: string): TraceDecoratorType { +export function infoDecorator(message: string): TraceDecoratorType { return createTracingDecorator({ message, opts: DEFAULT_OPTS, level: LogLevel.Info }); } -export function traceDecoratorWarn(message: string): TraceDecoratorType { +export function warnDecorator(message: string): TraceDecoratorType { return createTracingDecorator({ message, opts: DEFAULT_OPTS, level: LogLevel.Warning }); } @@ -302,14 +309,14 @@ export function ignoreLogging() { }); }; } -export function createTracingDecorator(logInfo: LogInfo) { +function createTracingDecorator(logInfo: LogInfo) { return traceDecorator( (call, traced) => logResult(logInfo, traced, call), (logInfo.opts & TraceOptions.BeforeCall) > 0 ); } -export type LogInfo = { +type LogInfo = { opts: TraceOptions; message: string; level?: LogLevel; @@ -421,17 +428,17 @@ function logResult(info: LogInfo, traced: TraceInfo, call?: CallInfo) { function logTo(logLevel: LogLevel, message: string, ...args: Arguments): void { switch (logLevel) { case LogLevel.Error: - traceError(message, ...args); + logger.error(message, ...args); break; case LogLevel.Warning: - traceWarning(message, ...args); + logWarning(message, ...args); break; case LogLevel.Info: - traceInfo(message, ...args); + logger.info(message, ...args); break; case LogLevel.Debug: case LogLevel.Trace: - traceVerbose(message, ...args); + logger.debug(message, ...args); break; default: break; diff --git a/src/platform/logging/outputChannelLogger.ts b/src/platform/logging/outputChannelLogger.ts index 0703bb6483a..a9278b7cd70 100644 --- a/src/platform/logging/outputChannelLogger.ts +++ b/src/platform/logging/outputChannelLogger.ts @@ -43,11 +43,15 @@ export class OutputChannelLogger implements ILogger { this.channel.appendLine(this.format('info', message, ...data)); } - public verbose(message: string, ...data: Arguments): void { + public debug(message: string, ...data: Arguments): void { this.channel.appendLine(this.format('debug', message, ...data)); } public trace(message: string, ...data: Arguments): void { this.channel.appendLine(this.format('trace', message, ...data)); } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + public ci(_message: any, ..._data: Arguments): void { + // + } } diff --git a/src/platform/logging/types.ts b/src/platform/logging/types.ts index 8bca7147892..bb8717b6547 100644 --- a/src/platform/logging/types.ts +++ b/src/platform/logging/types.ts @@ -10,8 +10,11 @@ export interface ILogger { error(message: string, ...data: Arguments): void; warn(message: string, ...data: Arguments): void; info(message: string, ...data: Arguments): void; - verbose(message: string, ...data: Arguments): void; + debug(message: string, ...data: Arguments): void; trace(message: string, ...data: Arguments): void; + ci(msg: () => [message: string, ...args: string[]] | string): void; + ci(message: string, ...args: string[]): void; + ci(arg1: any, ...args: Arguments): void; } export type TraceDecoratorType = ( diff --git a/src/platform/progress/decorator.ts b/src/platform/progress/decorator.ts index 0e514170088..4ce4eb2bdf0 100644 --- a/src/platform/progress/decorator.ts +++ b/src/platform/progress/decorator.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { traceError } from '../logging'; +import { logger } from '../logging'; import { PromiseFunction } from '../common/utils/async'; import { IProgressReporter, Progress, ReportableAction } from './types'; @@ -19,7 +19,7 @@ function report(progress: Progress) { try { _reporters.forEach((item) => item.report(progress)); } catch (ex) { - traceError('Failed to report progress', ex); + logger.error('Failed to report progress', ex); } } diff --git a/src/platform/progress/kernelProgressReporter.ts b/src/platform/progress/kernelProgressReporter.ts index bcb1106b162..e6cd3d0b85e 100644 --- a/src/platform/progress/kernelProgressReporter.ts +++ b/src/platform/progress/kernelProgressReporter.ts @@ -9,7 +9,7 @@ import { dispose } from '../common/utils/lifecycle'; import { IDisposable, IDisposableRegistry, Resource } from '../common/types'; import { createDeferred } from '../common/utils/async'; import { noop } from '../common/utils/misc'; -import { traceError } from '../logging'; +import { logger } from '../logging'; import { getComparisonKey } from '../vscode-path/resources'; import { getUserMessageForAction } from './messages'; import { ReportableAction } from './types'; @@ -163,7 +163,7 @@ export class KernelProgressReporter implements IExtensionSyncActivationService { progressInfo.dispose(); } } catch (ex) { - traceError(`Failed to dispose Progress reporter for ${key}`, ex); + logger.error(`Failed to dispose Progress reporter for ${key}`, ex); } } }; diff --git a/src/platform/telemetry/helpers.ts b/src/platform/telemetry/helpers.ts index 8903882de40..d4b0b594800 100644 --- a/src/platform/telemetry/helpers.ts +++ b/src/platform/telemetry/helpers.ts @@ -3,7 +3,7 @@ import { Environment } from '@vscode/python-extension'; import { computeHash } from '../common/crypto'; -import { traceError } from '../logging'; +import { logger } from '../logging'; export function getTelemetrySafeVersion(version: string | Environment['version']): string { if (typeof version === 'string') { @@ -20,7 +20,7 @@ export function getTelemetrySafeVersion(version: string | Environment['version'] } return `${major}.${minor}.${patch}`; } catch (ex) { - traceError(`Failed to parse version ${version}`, ex); + logger.error(`Failed to parse version ${version}`, ex); return ''; } } diff --git a/src/platform/telemetry/index.ts b/src/platform/telemetry/index.ts index aea1861822a..95b1ef42de1 100644 --- a/src/platform/telemetry/index.ts +++ b/src/platform/telemetry/index.ts @@ -3,7 +3,7 @@ import type TelemetryReporter from '@vscode/extension-telemetry'; import { AppinsightsKey, Telemetry, isTestExecution, isUnitTestExecution } from '../common/constants'; -import { traceError } from '../logging'; +import { logger } from '../logging'; import { StopWatch } from '../common/utils/stopWatch'; import { ExcludeType, noop, PickType, UnionToIntersection } from '../common/utils/misc'; import { populateTelemetryWithErrorInfo } from '../errors'; @@ -107,7 +107,7 @@ function sanitizeProperties(eventName: string, data: Record) { ? 'object' : data[prop].toString(); } catch (ex) { - traceError(`Failed to serialize ${prop} for ${eventName}`, ex); + logger.error(`Failed to serialize ${prop} for ${eventName}`, ex); } }); return customProperties; diff --git a/src/platform/telemetry/startupTelemetry.ts b/src/platform/telemetry/startupTelemetry.ts index 7c7483a1cfa..c7a5bd75210 100644 --- a/src/platform/telemetry/startupTelemetry.ts +++ b/src/platform/telemetry/startupTelemetry.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { isTestExecution } from '../common/constants'; -import { traceError } from '../logging'; +import { logger } from '../logging'; import { sendTelemetryEvent } from '.'; import { EventName } from './constants'; import { workspace } from 'vscode'; @@ -38,7 +38,7 @@ export function sendStartupTelemetry( updateActivationTelemetryProps(durations); sendTelemetryEvent(EventName.EXTENSION_LOAD, durations); } catch (ex) { - traceError('sendStartupTelemetry() failed.', ex); + logger.error('sendStartupTelemetry() failed.', ex); } } @@ -63,7 +63,7 @@ export function sendErrorTelemetry( updateActivationTelemetryProps(durations); sendTelemetryEvent(EventName.EXTENSION_LOAD, durations, props, ex); } catch (exc2) { - traceError('sendErrorTelemetry() failed.', exc2); + logger.error('sendErrorTelemetry() failed.', exc2); } } diff --git a/src/platform/telemetry/telemetry.ts b/src/platform/telemetry/telemetry.ts index f92b717c509..df467ee01a9 100644 --- a/src/platform/telemetry/telemetry.ts +++ b/src/platform/telemetry/telemetry.ts @@ -10,7 +10,7 @@ import { PythonEnvironment } from '../pythonEnvironments/info'; import { createDeferred } from '../common/utils/async'; import { getResourceType } from '../common/utils'; import { getComparisonKey } from '../vscode-path/resources'; -import { traceError } from '../logging'; +import { logger } from '../logging'; type Context = { previouslySelectedKernelConnectionId: string; @@ -56,7 +56,7 @@ export function updatePythonPackages( */ async function getPythonEnvironmentPackages(options: { interpreter: PythonEnvironment } | { interpreterHash: string }) { if (!_interpreterPackageProvider) { - traceError(`Python package provider is not initialized.`); + logger.error(`Python package provider is not initialized.`); return '{}'; } let interpreter: PythonEnvironment | undefined; diff --git a/src/platform/terminals/codeExecution/codeExecutionHelper.node.ts b/src/platform/terminals/codeExecution/codeExecutionHelper.node.ts index eec6ff1a957..167513100f2 100644 --- a/src/platform/terminals/codeExecution/codeExecutionHelper.node.ts +++ b/src/platform/terminals/codeExecution/codeExecutionHelper.node.ts @@ -4,7 +4,7 @@ import { inject, injectable } from 'inversify'; import { Uri } from 'vscode'; -import { traceError } from '../../logging'; +import { logger } from '../../logging'; import * as internalScripts from '../../interpreter/internal/scripts/index.node'; import { getFilePath } from '../../common/platform/fs-paths'; import { CodeExecutionHelperBase } from './codeExecutionHelper'; @@ -93,7 +93,7 @@ export class CodeExecutionHelper extends CodeExecutionHelperBase { } return normalizedLines; } catch (ex) { - traceError(ex, 'Python: Failed to normalize code for execution in Interactive Window'); + logger.error(ex, 'Python: Failed to normalize code for execution in Interactive Window'); return code; } finally { dispose(disposables); diff --git a/src/platform/webviews/webview.ts b/src/platform/webviews/webview.ts index 57e7517df88..d50070be50a 100644 --- a/src/platform/webviews/webview.ts +++ b/src/platform/webviews/webview.ts @@ -10,7 +10,7 @@ import { WebviewView as vscodeWebviewView } from 'vscode'; import { IWebview, IWebviewOptions, WebviewMessage } from '../common/application/types'; -import { traceError } from '../logging'; +import { logger } from '../logging'; import { Identifiers } from '../common/constants'; import { IFileSystem } from '../common/platform/types'; import { IDisposableRegistry } from '../common/types'; @@ -136,7 +136,7 @@ export abstract class Webview implements IWebview { } catch (error) { // If our web panel failes to load, report that out so whatever // is hosting the panel can clean up - traceError(`Error Loading WebviewPanel: ${error}`); + logger.error(`Error Loading WebviewPanel: ${error}`); this.loadFailedEmitter.fire(); } } diff --git a/src/standalone/activation/activationManager.ts b/src/standalone/activation/activationManager.ts index 4bfa038a2fb..22002f3eed0 100644 --- a/src/standalone/activation/activationManager.ts +++ b/src/standalone/activation/activationManager.ts @@ -3,7 +3,7 @@ import { injectable, multiInject, optional } from 'inversify'; import { IExtensionActivationManager, IExtensionSyncActivationService } from '../../platform/activation/types'; -import { traceError } from '../../platform/logging'; +import { logger } from '../../platform/logging'; /** * Responsible for calling the 'activate' method on all of the IExtensionSyncActivationServices. @@ -21,7 +21,7 @@ export class ExtensionActivationManager implements IExtensionActivationManager { try { item.activate(); } catch (ex) { - traceError(`Error in activating extension, failed in ${(item as Object).constructor.name}`, ex); + logger.error(`Error in activating extension, failed in ${(item as Object).constructor.name}`, ex); } }); } diff --git a/src/standalone/activation/workspaceActivation.node.ts b/src/standalone/activation/workspaceActivation.node.ts index 0751d645bd0..a1133dd7c03 100644 --- a/src/standalone/activation/workspaceActivation.node.ts +++ b/src/standalone/activation/workspaceActivation.node.ts @@ -6,7 +6,7 @@ import { TextDocument, workspace } from 'vscode'; import { sendActivationTelemetry } from '../../platform/telemetry/envFileTelemetry.node'; import { PYTHON_LANGUAGE } from '../../platform/common/constants'; import { IDisposable, Resource } from '../../platform/common/types'; -import { traceDecoratorError } from '../../platform/logging'; +import { errorDecorator } from '../../platform/logging'; import { IExtensionSyncActivationService } from '../../platform/activation/types'; import { IFileSystem } from '../../platform/common/platform/types'; import { noop } from '../../platform/common/utils/misc'; @@ -40,7 +40,7 @@ export class WorkspaceActivation implements IExtensionSyncActivationService { : undefined; } - @traceDecoratorError('Failed to activate a workspace') + @errorDecorator('Failed to activate a workspace') public async activateWorkspace(resource: Resource) { const key = this.getWorkspaceKey(resource); if (this.activatedWorkspaces.has(key)) { diff --git a/src/standalone/api/kernels/api.vscode.common.test.ts b/src/standalone/api/kernels/api.vscode.common.test.ts index 0e2e3727aa0..612ab754c05 100644 --- a/src/standalone/api/kernels/api.vscode.common.test.ts +++ b/src/standalone/api/kernels/api.vscode.common.test.ts @@ -3,7 +3,7 @@ import { assert } from 'chai'; import { CancellationTokenSource, NotebookCellOutputItem, NotebookDocument, commands, window, workspace } from 'vscode'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IDisposable } from '../../../platform/common/types'; import { captureScreenShot, @@ -44,7 +44,7 @@ suiteMandatory('Kernel API Tests @typescript', function () { let controllerRegistration: IControllerRegistration; suiteSetup(async function () { this.timeout(120_000); - traceInfo('Suite Setup, Step 1'); + logger.info('Suite Setup, Step 1'); const api = await initialize(); kernelProvider = api.serviceContainer.get(IKernelProvider); controllerRegistration = api.serviceContainer.get(IControllerRegistration); @@ -59,10 +59,10 @@ suiteMandatory('Kernel API Tests @typescript', function () { 'Deno kernel not found' ); controller = controllerRegistration.get(connection, 'jupyter-notebook')!; - traceInfo('Suite Setup (completed)'); + logger.info('Suite Setup (completed)'); }); setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); const uri = await createTemporaryNotebook( [], disposables, @@ -83,17 +83,17 @@ suiteMandatory('Kernel API Tests @typescript', function () { metadata: controller.connection, resourceUri: notebook.uri }); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); if (this.currentTest?.isFailed()) { await captureScreenShot(this); } await closeNotebooksAndCleanUpAfterTests(disposables); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); testMandatory('No kernel returned if no code has been executed', async function () { const kernel = await kernels.getKernel(notebook.uri); @@ -127,11 +127,11 @@ suiteMandatory('Kernel API Tests @typescript', function () { const statusChange = createEventHandler(kernel, 'onDidChangeStatus', disposables); // Verify we can execute code using the kernel. - traceInfo(`Execute code silently`); + logger.info(`Execute code silently`); const expectedMime = NotebookCellOutputItem.stdout('').mime; const token = new CancellationTokenSource(); await waitForOutput(kernel.executeCode('console.log(1234)', token.token), '1234', expectedMime); - traceInfo(`Execute code silently completed`); + logger.info(`Execute code silently completed`); // Wait for kernel to be idle. await waitForCondition( () => kernel.status === 'idle', @@ -227,16 +227,16 @@ suiteMandatory('Kernel API Tests @typescript/@python', function () { let controllerRegistration: IControllerRegistration; suiteSetup(async function () { this.timeout(120_000); - traceInfo('Suite Setup, Step 1'); + logger.info('Suite Setup, Step 1'); const api = await initialize(); controllerRegistration = api.serviceContainer.get(IControllerRegistration); kernels = await Promise.resolve(getKernelsApi(JVSC_EXTENSION_ID_FOR_TESTS)); const pythonMetadata = await getDefaultKernelConnection(); controller = controllerRegistration.get(pythonMetadata, 'jupyter-notebook')!; - traceInfo('Suite Setup (completed)'); + logger.info('Suite Setup (completed)'); }); setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); const uri = await createTemporaryNotebook([], disposables); notebook = await workspace.openNotebookDocument(uri); await window.showNotebookDocument(notebook); @@ -245,17 +245,17 @@ suiteMandatory('Kernel API Tests @typescript/@python', function () { extension: JVSC_EXTENSION_ID }); await insertCodeCell('print(1234)', { index: 0, language: 'python' }); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); if (this.currentTest?.isFailed()) { await captureScreenShot(this); } await closeNotebooksAndCleanUpAfterTests(disposables); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); testMandatory('Execute chat code', async function () { // Ensure user has executed some code against this kernel. @@ -290,7 +290,7 @@ step1() // Verify we can execute code using the kernel. const callbacksInvoked: string[] = []; const callbackArgs: (string | undefined)[] = []; - traceInfo(`Execute code`); + logger.info(`Execute code`); const token = new CancellationTokenSource(); const handlers = { callback1: async (data?: string) => { diff --git a/src/standalone/api/kernels/apiAccess.ts b/src/standalone/api/kernels/apiAccess.ts index 5281212d823..9b928376230 100644 --- a/src/standalone/api/kernels/apiAccess.ts +++ b/src/standalone/api/kernels/apiAccess.ts @@ -4,7 +4,7 @@ import { EventEmitter, ExtensionMode, Uri, env, extensions, l10n, window, workspace } from 'vscode'; import { JVSC_EXTENSION_ID } from '../../../platform/common/constants'; import { ServiceContainer } from '../../../platform/ioc/container'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IDisposableRegistry, IExtensionContext } from '../../../platform/common/types'; import { once } from '../../../platform/common/utils/functional'; import { Common } from '../../../platform/common/utils/localize'; @@ -64,7 +64,7 @@ async function requestKernelAccessImpl( } const displayName = extensions.getExtension(extensionId)?.packageJSON?.displayName; if (!displayName) { - traceError(`Kernel API access revoked, as extension ${extensionId} does not exist!`); + logger.error(`Kernel API access revoked, as extension ${extensionId} does not exist!`); return { result: 'denied' }; } const allow = l10n.t('Allow'); @@ -145,7 +145,7 @@ async function getAccessForExtensionsFromStore(ignoreCache: boolean = false): Pr cachedAccessInfo = new Map(Object.entries(JSON.parse(json))); return cachedAccessInfo; } catch (ex) { - traceError(`Failed to parse API access information ${json}`, ex); + logger.error(`Failed to parse API access information ${json}`, ex); return new Map(); } } @@ -169,7 +169,7 @@ export async function updateListOfExtensionsAllowedToAccessApi(extensionIds: str await context.secrets.store(apiAccessSecretKey, JSON.stringify(Object.fromEntries(cachedAccessInfo))); onDidChange.fire(); } catch (ex) { - traceError( + logger.error( `Failed to update API access information ${JSON.stringify(Object.fromEntries(cachedAccessInfo))}`, ex ); @@ -192,7 +192,7 @@ async function updateIndividualExtensionAccessInStore(extensionId: string, acces await context.secrets.store(apiAccessSecretKey, JSON.stringify(Object.fromEntries(apiAccess))); onDidChange.fire(); } catch (ex) { - traceError(`Failed to store API access information ${JSON.stringify(Object.fromEntries(apiAccess))}`, ex); + logger.error(`Failed to store API access information ${JSON.stringify(Object.fromEntries(apiAccess))}`, ex); } })); } diff --git a/src/standalone/api/kernels/backgroundExecution.ts b/src/standalone/api/kernels/backgroundExecution.ts index 8e7a84432e1..04e8659e5bb 100644 --- a/src/standalone/api/kernels/backgroundExecution.ts +++ b/src/standalone/api/kernels/backgroundExecution.ts @@ -9,7 +9,7 @@ import { DisposableStore } from '../../../platform/common/utils/lifecycle'; import { raceCancellation } from '../../../platform/common/cancellation'; import { getNotebookCellOutputMetadata } from '../../../kernels/execution/helpers'; import { unTrackDisplayDataForExtension } from '../../../kernels/execution/extensionDisplayDataTracker'; -import { traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; export const executionCounters = new WeakMap(); export async function execCodeInBackgroundThread( @@ -105,7 +105,7 @@ del __jupyter_exec_background__ if (result?.mime === mimeFinalResult) { return JSON.parse(new TextDecoder().decode(result.data)) as T; } else if (result?.mime === mimeErrorResult) { - traceWarning('Error in background execution:\n', new TextDecoder().decode(result.data)); + logger.warn('Error in background execution:\n', new TextDecoder().decode(result.data)); return; } } @@ -114,7 +114,7 @@ del __jupyter_exec_background__ return; } if (!displayId) { - traceWarning('Failed to get display id for completions'); + logger.warn('Failed to get display id for completions'); return; } diff --git a/src/standalone/api/kernels/kernel.ts b/src/standalone/api/kernels/kernel.ts index 0ede54b45a1..d6847776bb6 100644 --- a/src/standalone/api/kernels/kernel.ts +++ b/src/standalone/api/kernels/kernel.ts @@ -30,7 +30,7 @@ import { Telemetry, sendTelemetryEvent } from '../../../telemetry'; import { StopWatch } from '../../../platform/common/utils/stopWatch'; import { Deferred, createDeferred, sleep } from '../../../platform/common/utils/async'; import { once } from '../../../platform/common/utils/events'; -import { traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { JVSC_EXTENSION_ID, POWER_TOYS_EXTENSION_ID, PYTHON_LANGUAGE } from '../../../platform/common/constants'; import { ChatMime, generatePythonCodeToInvokeCallback } from '../../../kernels/chat/generator'; import { @@ -408,7 +408,7 @@ class WrappedKernelPerExtension extends DisposableBase implements Kernel { measures.cancelledAfter = stopwatch.elapsedTime; properties.cancelledBeforeRequestSent = !properties.requestSent; properties.cancelledBeforeRequestAcknowledged = !properties.requestAcknowledged; - traceVerbose(`Code execution cancelled by extension ${this.extensionId}`); + logger.debug(`Code execution cancelled by extension ${this.extensionId}`); }, this, disposables diff --git a/src/standalone/api/unstable/api.jupyterProvider.vscode.test.ts b/src/standalone/api/unstable/api.jupyterProvider.vscode.test.ts index 9d082d32fbf..8918daae2d2 100644 --- a/src/standalone/api/unstable/api.jupyterProvider.vscode.test.ts +++ b/src/standalone/api/unstable/api.jupyterProvider.vscode.test.ts @@ -5,7 +5,7 @@ import * as sinon from 'sinon'; import { assert } from 'chai'; import { dispose } from '../../../platform/common/utils/lifecycle'; import { IDisposable, IExtensions } from '../../../platform/common/types'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IExtensionTestApi, waitForCondition } from '../../../test/common'; import { noop } from '../../../test/core'; import { initialize } from '../../../test/initialize'; @@ -61,7 +61,7 @@ suite('Jupyter Provider Tests', function () { return closeNotebooksAndCleanUpAfterTests(disposables); }); setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); sinon .stub(api.serviceContainer.get(IExtensions), 'determineExtensionFromCallStack') .returns({ extensionId: 'GitHub', displayName: 'Sample Extension' }); @@ -72,14 +72,14 @@ suite('Jupyter Provider Tests', function () { nbProviders.push({ provider, disposable }); return disposable; }); - traceInfo(`Start Test Completed ${this.currentTest?.title}`); + logger.info(`Start Test Completed ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`End Test ${this.currentTest?.title}`); + logger.info(`End Test ${this.currentTest?.title}`); sinon.restore(); dispose(disposables); - traceInfo(`End Test Completed ${this.currentTest?.title}`); + logger.info(`End Test Completed ${this.currentTest?.title}`); }); test('Verify Kernel Source Action is registered & unregistered for the 3rd party extension', async () => { const serverProvider1 = { diff --git a/src/standalone/api/unstable/apiAccessService.ts b/src/standalone/api/unstable/apiAccessService.ts index 5fcc7740e8f..dd5275d28b8 100644 --- a/src/standalone/api/unstable/apiAccessService.ts +++ b/src/standalone/api/unstable/apiAccessService.ts @@ -8,7 +8,7 @@ import { GLOBAL_MEMENTO, IExtensionContext, IMemento } from '../../../platform/c import { PromiseChain } from '../../../platform/common/utils/async'; import { Common, DataScience } from '../../../platform/common/utils/localize'; import { sendTelemetryEvent } from '../../../telemetry'; -import { traceError, traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { noop } from '../../../platform/common/utils/misc'; import { extensions } from 'vscode'; import { getVSCodeChannel } from '../../../platform/common/application/applicationEnvironment'; @@ -51,7 +51,7 @@ export class ApiAccessService { !info.extensionId || info.extensionId === unknownExtensionId ? '' : info.extensionId.split('.')[0] || ''; if (this.context.extensionMode === ExtensionMode.Test || !publisherId || getVSCodeChannel() === 'insiders') { if (!TrustedExtensionPublishers.has(publisherId) && !PublishersAllowedWithPrompts.has(publisherId)) { - traceWarning(`Publisher ${publisherId} is allowed to access the Kernel API with a message.`); + logger.warn(`Publisher ${publisherId} is allowed to access the Kernel API with a message.`); const displayName = extensions.getExtension(info.extensionId)?.packageJSON?.displayName || ''; const extensionDisplay = displayName && info.extensionId @@ -83,7 +83,7 @@ export class ApiAccessService { `Please contact the Jupyter Extension to get access to the Kernel API. Publisher ${publisherId}` ) .then(noop, noop); - traceError(`Publisher ${publisherId} is not allowed to access the Kernel API.`); + logger.error(`Publisher ${publisherId} is not allowed to access the Kernel API.`); return { extensionId: info.extensionId, accessAllowed: false }; } const extensionPermissions = this.globalState.get(API_ACCESS_GLOBAL_KEY); diff --git a/src/standalone/api/unstable/index.ts b/src/standalone/api/unstable/index.ts index dfe30523068..88528c16cf7 100644 --- a/src/standalone/api/unstable/index.ts +++ b/src/standalone/api/unstable/index.ts @@ -6,7 +6,7 @@ import { CodespacesJupyterServerSelector } from '../../../codespaces/codeSpacesS import { CodespaceExtensionId, JVSC_EXTENSION_ID, Telemetry } from '../../../platform/common/constants'; import { IDisposable, IExtensions } from '../../../platform/common/types'; import { IServiceContainer } from '../../../platform/ioc/types'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IControllerRegistration, ILocalPythonNotebookKernelSourceSelector @@ -47,7 +47,7 @@ export function registerRemoteServerProvider( const extensionId = provider.id.startsWith('_builtin') ? JVSC_EXTENSION_ID : extensions.determineExtensionFromCallStack().extensionId; - traceError( + logger.error( `The API registerRemoteServerProvider has being deprecated and will be removed soon, please use createJupyterServerCollection (extension ${extensionId}).` ); if (extensionId.toLowerCase() != CodespaceExtensionId.toLowerCase()) { @@ -78,7 +78,7 @@ export function getReady(ready: Promise): Promise { return ready .then(() => noop()) .catch((ex) => { - traceError('Failure during activation.', ex); + logger.error('Failure during activation.', ex); return Promise.reject(ex); }); } @@ -93,7 +93,7 @@ export function getKernelService(serviceContainer: IServiceContainer) { } export async function addRemoteJupyterServer(providerId: string, handle: string, serviceContainer: IServiceContainer) { const extensions = serviceContainer.get(IExtensions); - traceError( + logger.error( 'The API addRemoteJupyterServer has being deprecated and will be removed soon, please use createJupyterServerCollection.' ); const extensionId = extensions.determineExtensionFromCallStack().extensionId; diff --git a/src/standalone/api/unstable/kernelApi.ts b/src/standalone/api/unstable/kernelApi.ts index 0c20b93dff3..fb10d2707d6 100644 --- a/src/standalone/api/unstable/kernelApi.ts +++ b/src/standalone/api/unstable/kernelApi.ts @@ -10,7 +10,7 @@ import { BaseKernelConnectionMetadata, IKernelFinder } from '../../../kernels/types'; -import { traceVerbose, traceInfoIfCI } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IDisposableRegistry, IExtensions } from '../../../platform/common/types'; import { PromiseChain } from '../../../platform/common/utils/async'; import { sendTelemetryEvent } from '../../../telemetry'; @@ -78,7 +78,7 @@ class JupyterKernelService implements IExportedKernelService { extensionId: this.callingExtensionId, pemUsed: 'onDidChangeKernelSpecifications' }); - traceVerbose(`API called from ${this.callingExtensionId}`); + logger.debug(`API called from ${this.callingExtensionId}`); return this._onDidChangeKernelSpecifications.event; } public get onDidChangeKernels(): Event { @@ -117,7 +117,7 @@ class JupyterKernelService implements IExportedKernelService { ); this.kernelProvider.onDidDisposeKernel( (e) => { - traceInfoIfCI( + logger.ci( `Kernel ${ e.kernelConnectionMetadata.id }, ${e.kernelConnectionMetadata.interpreter?.uri.toString()} disposed` @@ -129,7 +129,7 @@ class JupyterKernelService implements IExportedKernelService { ); this.kernelProvider.onDidStartKernel( (e) => { - traceInfoIfCI( + logger.ci( `Kernel ${ e.kernelConnectionMetadata.id }, ${e.kernelConnectionMetadata.interpreter?.uri.toString()} started` @@ -141,7 +141,7 @@ class JupyterKernelService implements IExportedKernelService { ); this.thirdPartyKernelProvider.onDidDisposeKernel( (e) => { - traceInfoIfCI( + logger.ci( `Third party Kernel ${ e.kernelConnectionMetadata.id }, ${e.kernelConnectionMetadata.interpreter?.uri.toString()} disposed` @@ -153,7 +153,7 @@ class JupyterKernelService implements IExportedKernelService { ); this.thirdPartyKernelProvider.onDidStartKernel( (e) => { - traceInfoIfCI( + logger.ci( `Third party Kernel ${ e.kernelConnectionMetadata.id }, ${e.kernelConnectionMetadata.interpreter?.uri.toString()} started` diff --git a/src/standalone/chat/extesnion.ts b/src/standalone/chat/extesnion.ts index c5caa39c492..885479ea2ef 100644 --- a/src/standalone/chat/extesnion.ts +++ b/src/standalone/chat/extesnion.ts @@ -8,7 +8,7 @@ import { execCodeInBackgroundThread } from '../api/kernels/backgroundExecution'; import { ServiceContainer } from '../../platform/ioc/container'; import { IControllerRegistration } from '../../notebooks/controllers/types'; import { JupyterVariablesProvider } from '../variables/JupyterVariablesProvider'; -import { traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; export async function activate(context: vscode.ExtensionContext): Promise { context.subscriptions.push( @@ -26,7 +26,7 @@ export async function activate(context: vscode.ExtensionContext): Promise } } catch (ex) { // ignore - traceWarning('Failed to get pip packages', ex); + logger.warn('Failed to get pip packages', ex); } } } diff --git a/src/standalone/devTools/clearCache.ts b/src/standalone/devTools/clearCache.ts index 7f55d07d4b9..89d4389d54f 100644 --- a/src/standalone/devTools/clearCache.ts +++ b/src/standalone/devTools/clearCache.ts @@ -5,7 +5,7 @@ import { Uri, commands, workspace } from 'vscode'; import { IExtensionContext } from '../../platform/common/types'; import { noop } from '../../platform/common/utils/misc'; import { Commands } from '../../platform/common/constants'; -import { traceInfo } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { RemoteKernelSpecCacheFileName } from '../../kernels/jupyter/constants'; export function addClearCacheCommand(context: IExtensionContext, isDevMode: boolean) { @@ -30,6 +30,6 @@ export function addClearCacheCommand(context: IExtensionContext, isDevMode: bool workspace.fs.delete(Uri.joinPath(context.globalStorageUri, 'remoteServersMRUList.json')).then(noop, noop), workspace.fs.delete(Uri.joinPath(context.globalStorageUri, RemoteKernelSpecCacheFileName)).then(noop, noop) ]); - traceInfo('Cache cleared'); + logger.info('Cache cleared'); }); } diff --git a/src/standalone/devTools/jupyterOutputChannel.ts b/src/standalone/devTools/jupyterOutputChannel.ts index 058ea9702d7..e11758cc3a3 100644 --- a/src/standalone/devTools/jupyterOutputChannel.ts +++ b/src/standalone/devTools/jupyterOutputChannel.ts @@ -4,7 +4,7 @@ import { window } from 'vscode'; import { IDisposableRegistry, IOutputChannel } from '../../platform/common/types'; import * as localize from '../../platform/common/utils/localize'; -import { traceVerbose } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { splitLines } from '../../platform/common/helpers'; /** @@ -41,12 +41,12 @@ export function getJupyterOutputChannel(disposables: IDisposableRegistry): IOutp function formatMessageAndLog(...args: Parameters) { if (args.length === 1) { - traceVerbose( + logger.debug( splitLines(args[0]) .map((line, i) => (i === 0 ? line : ` ${line}`)) .join('\n') ); } else { - traceVerbose(...args); + logger.debug(...args); } } diff --git a/src/standalone/import-export/exportCommands.ts b/src/standalone/import-export/exportCommands.ts index 2a51cbaaa67..3c92e27c3ab 100644 --- a/src/standalone/import-export/exportCommands.ts +++ b/src/standalone/import-export/exportCommands.ts @@ -13,7 +13,7 @@ import { } from 'vscode'; import * as localize from '../../platform/common/utils/localize'; import { ICommandNameArgumentTypeMapping } from '../../commands'; -import { traceInfo } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IDisposable } from '../../platform/common/types'; import { DataScience } from '../../platform/common/utils/localize'; import { isUri, noop } from '../../platform/common/utils/misc'; @@ -118,7 +118,7 @@ export class ExportCommands implements IDisposable { window.activeNotebookEditor?.notebook || this.interactiveProvider?.getActiveOrAssociatedInteractiveWindow()?.notebookDocument; if (!sourceDocument) { - traceInfo('Export called without a valid exportable document active'); + logger.info('Export called without a valid exportable document active'); return; } diff --git a/src/standalone/import-export/jupyterExporter.ts b/src/standalone/import-export/jupyterExporter.ts index 3689b24de41..d0dbe38dc23 100644 --- a/src/standalone/import-export/jupyterExporter.ts +++ b/src/standalone/import-export/jupyterExporter.ts @@ -5,7 +5,7 @@ import type * as nbformat from '@jupyterlab/nbformat'; import { inject, injectable, optional } from 'inversify'; import { NotebookData, Uri, extensions, window, type NotebookCellData } from 'vscode'; -import { traceError } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IFileSystem } from '../../platform/common/platform/types'; import { DataScience } from '../../platform/common/utils/localize'; import { defaultNotebookFormat } from '../../platform/common/constants'; @@ -48,7 +48,7 @@ export class JupyterExporter implements INotebookExporter { } }, noop); } catch (exc) { - traceError('Error in exporting notebook file'); + logger.error('Error in exporting notebook file'); window .showInformationMessage( // eslint-disable-next-line @typescript-eslint/no-explicit-any diff --git a/src/standalone/intellisense/kernelCompletionProvider.ts b/src/standalone/intellisense/kernelCompletionProvider.ts index 7241e639204..d02b3b531ce 100644 --- a/src/standalone/intellisense/kernelCompletionProvider.ts +++ b/src/standalone/intellisense/kernelCompletionProvider.ts @@ -20,7 +20,7 @@ import { workspace } from 'vscode'; import { raceCancellation } from '../../platform/common/cancellation'; -import { traceInfoIfCI, traceVerbose, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IDisposable, IDisposableRegistry, Resource } from '../../platform/common/types'; import { StopWatch } from '../../platform/common/utils/stopWatch'; import { IKernelProvider, IKernel } from '../../kernels/types'; @@ -144,7 +144,7 @@ class NotebookCellSpecificKernelCompletionProvider implements CompletionItemProv return []; } if (!(ex instanceof CancellationError)) { - traceVerbose(`Completions failed`, ex); + logger.debug(`Completions failed`, ex); } throw ex; } finally { @@ -188,7 +188,7 @@ class NotebookCellSpecificKernelCompletionProvider implements CompletionItemProv properties.requestSent = true; const kernelCompletions = await raceCancellation(token, this.getKernelCompletion(code, cursor_pos, token)); - traceVerbose(`Jupyter completion time: ${stopWatch.elapsedTime}`); + logger.debug(`Jupyter completion time: ${stopWatch.elapsedTime}`); properties.cancelled = token.isCancellationRequested; properties.completed = !token.isCancellationRequested; properties.kernelStatusAfterRequest = this.kernel.status; @@ -427,7 +427,7 @@ class KernelSpecificCompletionProvider extends DisposableBase implements Complet return; } - traceVerbose( + logger.debug( `Registering Kernel Completion Provider from kernel ${getDisplayNameOrNameOfKernelConnection( this.kernel.kernelConnectionMetadata )} for language ${this.monacoLanguage}` @@ -579,7 +579,7 @@ function logHowToEnableKernelCompletion(kernel: IKernel) { const kernelLanguage = getKernelLanguage(kernel); const monacoLanguage = getKernelLanguageAsMonacoLanguage(kernel); if (kernelLanguage.toLowerCase() === monacoLanguage.toLowerCase()) { - traceWarning( + logger.warn( l10n.t( `Kernel completions not enabled for '{0}'. \nTo enable Kernel completion for this language please add the following setting \njupyter.completionTriggerCharacters = {1}: []}. \nFor more information please see https://aka.ms/vscodeJupyterCompletion`, getDisplayNameOrNameOfKernelConnection(kernel.kernelConnectionMetadata), @@ -587,7 +587,7 @@ function logHowToEnableKernelCompletion(kernel: IKernel) { ) ); } else { - traceWarning( + logger.warn( l10n.t( `Kernel completions not enabled for '{0}'. \nTo enable Kernel completion for this language please add the following setting \njupyter.completionTriggerCharacters = {1}: []}. \n or the following: \njupyter.completionTriggerCharacters = {2}: []}. \nFor more information please see https://aka.ms/vscodeJupyterCompletion`, getDisplayNameOrNameOfKernelConnection(kernel.kernelConnectionMetadata), @@ -636,7 +636,7 @@ export function generatePythonCompletions( allowStringFilter && (triggerCharacter == "'" || triggerCharacter == '"' || positionInsideString(line, position)); - traceInfoIfCI(`Jupyter completions filtering applied: ${insideString} on ${line}`); + logger.ci(`Jupyter completions filtering applied: ${insideString} on ${line}`); // Update magics to have a much lower sort order than other strings. // Also change things that start with our current word to eliminate the @@ -731,13 +731,13 @@ export function generatePythonCompletions( }) .filter((r) => r !== undefined) as CompletionItem[]; - traceInfoIfCI( + logger.ci( `Jupyter completions for ${word} at pos ${position.line}:${ position.character } with trigger: ${triggerCharacter}\n ${completions.map((r) => r.label).join(',')}` ); - traceInfoIfCI( + logger.ci( `Jupyter results for ${word} at pos ${position.line}:${ position.character } with trigger: ${triggerCharacter}\n ${result.map((r) => r.label).join(',')}` diff --git a/src/standalone/intellisense/notebookPythonPathService.node.ts b/src/standalone/intellisense/notebookPythonPathService.node.ts index 34dc09507f7..5d9cd254db8 100644 --- a/src/standalone/intellisense/notebookPythonPathService.node.ts +++ b/src/standalone/intellisense/notebookPythonPathService.node.ts @@ -8,7 +8,7 @@ import { IExtensionSyncActivationService } from '../../platform/activation/types import { IPythonApiProvider, IPythonExtensionChecker } from '../../platform/api/types'; import { PylanceExtension } from '../../platform/common/constants'; import { getDisplayPath, getFilePath } from '../../platform/common/platform/fs-paths'; -import { traceVerbose } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IControllerRegistration } from '../../notebooks/controllers/types'; import { IKernelProvider, isRemoteConnection } from '../../kernels/types'; import { noop } from '../../platform/common/utils/misc'; @@ -133,7 +133,7 @@ del _VSCODE_os, _VSCODE_sys, _VSCODE_builtins if (!executable || !(await fs.pathExists(executable))) { return; } - traceVerbose( + logger.debug( `Remote Interpreter for Pylance for Notebook URI "${getDisplayPath(notebook.uri)}" is ${getDisplayPath( executable )}` @@ -146,10 +146,10 @@ del _VSCODE_os, _VSCODE_sys, _VSCODE_builtins if (!interpreter) { // Empty string is special, means do not use any interpreter at all. - traceVerbose(`No interpreter for Pylance for Notebook URI "${getDisplayPath(notebook.uri)}"`); + logger.debug(`No interpreter for Pylance for Notebook URI "${getDisplayPath(notebook.uri)}"`); return ''; } - traceVerbose( + logger.debug( `Interpreter for Pylance for Notebook URI "${getDisplayPath(notebook.uri)}" is ${getDisplayPath( interpreter.uri )}` diff --git a/src/standalone/intellisense/resolveCompletionItem.ts b/src/standalone/intellisense/resolveCompletionItem.ts index be7e3e55c2c..f7f99c8b4dd 100644 --- a/src/standalone/intellisense/resolveCompletionItem.ts +++ b/src/standalone/intellisense/resolveCompletionItem.ts @@ -10,7 +10,7 @@ import { raceTimeoutError } from '../../platform/common/utils/async'; import { raceCancellation, wrapCancellationTokens } from '../../platform/common/cancellation'; import { DisposableStore, dispose } from '../../platform/common/utils/lifecycle'; import { stripAnsi } from '../../platform/common/utils/regexp'; -import { traceInfo, traceVerbose, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { getDisplayNameOrNameOfKernelConnection, isPythonKernelConnection } from '../../kernels/helpers'; import { Settings } from '../../platform/common/constants'; import { convertDocumentationToMarkdown } from './completionDocumentationFormatter'; @@ -108,7 +108,7 @@ function handleKernelRequestTimeout(kernel: IKernel, monacoLanguage: string, ker return; } kernelsThatDoNotSupportCompletionResolveOrAreTooSlowToReply.add(kernel); - traceWarning( + logger.warn( `Failed to inspect code in kernel ${getDisplayNameOrNameOfKernelConnection(kernel.kernelConnectionMetadata)}` ); if (!telemetrySentForUnableToResolveCompletion.has(kernel)) { @@ -201,7 +201,7 @@ function shoudlSendInspectRequest(kernel: IKernel) { !isPythonKernelConnection(kernel.kernelConnectionMetadata) && times.maxTime > maxTimeWaitingForResolveCompletion ) { - traceWarning( + logger.warn( `Not sending inspect request as previous requests took over ${maxTimeWaitingForResolveCompletion}s.` ); return false; @@ -211,7 +211,7 @@ function shoudlSendInspectRequest(kernel: IKernel) { // Ok we know that at least 5 requests took more than ?s. // Do not send another request at all. // No point in causing unnecessary load on the kernel. - traceWarning( + logger.warn( `Not sending inspect request as there have been at least ${maxNumberOfTimesAllowedToExceedTimeoutBeforeIgnoringAllRequests} requests that took over ${maxTimeWaitingForResolveCompletion}s.` ); return false; @@ -219,7 +219,7 @@ function shoudlSendInspectRequest(kernel: IKernel) { if (times.maxTime > maxTimeWaitingForResolveCompletion && Date.now() - times.lastRequestTime < 30_000) { // Ok we know that at least one request took more than 1s. // Do not send another request, lets wait for at least 30s before we send another request. - traceWarning( + logger.warn( `Not sending inspect request as previous requests took over ${maxTimeWaitingForResolveCompletion}s.` ); return false; @@ -234,7 +234,7 @@ async function waitForKernelToBeReady(kernel: IKernel, token: CancellationToken) if (!doesKernelHaveTooManyPendingRequests(kernel)) { return; } - traceInfo( + logger.info( `Too many pending requests ${getPendingRequestCount(kernel)} for kernel ${ kernel.id }, waiting for it to be ready.` @@ -323,7 +323,7 @@ async function sendInspectRequest( const stopWatch = new StopWatch(); const codeForLogging = splitLines(message.code).reverse()[0].slice(-50); - traceVerbose(`Inspecting code ${codeForLogging}`); + logger.debug(`Inspecting code ${codeForLogging}`); const request = isPythonKernelConnection(kernel.kernelConnectionMetadata) ? sendPythonInspectRequest(kernel, message, token) : kernel.session.kernel.requestInspect(message); @@ -338,11 +338,11 @@ async function sendInspectRequest( cachedResult(kernel, message, content); trackCompletionTime(kernel, stopWatch.elapsedTime); - const logger = stopWatch.elapsedTime > maxTimeWaitingForResolveCompletion ? traceWarning : traceVerbose; + const log = stopWatch.elapsedTime > maxTimeWaitingForResolveCompletion ? logger.warn : logger.debug; if (token.isCancellationRequested) { - logger(`Inspected code ${codeForLogging} in ${stopWatch.elapsedTime}ms (but cancelled)`); + log(`Inspected code ${codeForLogging} in ${stopWatch.elapsedTime}ms (but cancelled)`); } else { - logger(`Inspected code ${codeForLogging} in ${stopWatch.elapsedTime}ms`); + log(`Inspected code ${codeForLogging} in ${stopWatch.elapsedTime}ms`); } return content; }); diff --git a/src/standalone/survey/dataScienceSurveyBanner.node.ts b/src/standalone/survey/dataScienceSurveyBanner.node.ts index eacde1685e4..3e281e5770c 100644 --- a/src/standalone/survey/dataScienceSurveyBanner.node.ts +++ b/src/standalone/survey/dataScienceSurveyBanner.node.ts @@ -4,7 +4,7 @@ import { inject, injectable } from 'inversify'; import { Disposable, UIKind, env, window } from 'vscode'; import { IExtensionSyncActivationService } from '../../platform/activation/types'; -import { traceError } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { BannerType, IDisposableRegistry, @@ -76,7 +76,7 @@ export class DataScienceSurveyBanner implements IJupyterExtensionBanner, IExtens } break; default: - traceError('Invalid Banner Type'); + logger.error('Invalid Banner Type'); return false; } return false; @@ -195,7 +195,7 @@ export class DataScienceSurveyBanner implements IJupyterExtensionBanner, IExtens case BannerType.ExperimentNotebookSurvey: return this.getPersistentState(ExperimentNotebookSurveyStateKeys.ExecutionCount); default: - traceError('Invalid Banner type'); + logger.error('Invalid Banner type'); return -1; } } @@ -242,7 +242,7 @@ export class DataScienceSurveyBanner implements IJupyterExtensionBanner, IExtens case BannerType.ExperimentNotebookSurvey: return localize.InsidersNativeNotebooksSurveyBanner.bannerMessage; default: - traceError('Invalid Banner type'); + logger.error('Invalid Banner type'); return ''; } } @@ -254,7 +254,7 @@ export class DataScienceSurveyBanner implements IJupyterExtensionBanner, IExtens case BannerType.ExperimentNotebookSurvey: return 'https://aka.ms/vscnbexp'; default: - traceError('Invalid Banner type'); + logger.error('Invalid Banner type'); return ''; } } diff --git a/src/standalone/userJupyterHubServer/jupyterHubPasswordConnect.ts b/src/standalone/userJupyterHubServer/jupyterHubPasswordConnect.ts index 7e6600a5ce7..9118e918e6f 100644 --- a/src/standalone/userJupyterHubServer/jupyterHubPasswordConnect.ts +++ b/src/standalone/userJupyterHubServer/jupyterHubPasswordConnect.ts @@ -11,7 +11,7 @@ import { import { DataScience } from '../../platform/common/utils/localize'; import { noop } from '../../platform/common/utils/misc'; import { IMultiStepInputFactory, IMultiStepInput } from '../../platform/common/utils/multiStepInput'; -import { traceVerbose, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { sendTelemetryEvent, Telemetry } from '../../telemetry'; import { IJupyterRequestAgentCreator, @@ -70,7 +70,7 @@ export class JupyterHubPasswordConnect { result = this.getJupyterHubConnectionInfo(newUrl, options.validationErrorMessage).then((value) => { if (!value || (value.requiresPassword && Object.keys(value).length === 1)) { // If we fail to get a valid password connect info, don't save the value - traceWarning(`Password for ${newUrl} was invalid.`); + logger.warn(`Password for ${newUrl} was invalid.`); this.savedConnectInfo.delete(options.handle); } @@ -117,14 +117,14 @@ export class JupyterHubPasswordConnect { // Ensure we get a valid JSON with a version in it. try { const json = await response.json(); - traceVerbose(`JupyterHub version is ${json && json.version} for url ${url}`); + logger.debug(`JupyterHub version is ${json && json.version} for url ${url}`); return json && json.version; } catch { // } return false; } catch (ex) { - traceVerbose(`Error in detecting whether url is isJupyterHub: ${ex}`); + logger.debug(`Error in detecting whether url is isJupyterHub: ${ex}`); return false; } } diff --git a/src/standalone/userJupyterServer/jupyterPasswordConnect.ts b/src/standalone/userJupyterServer/jupyterPasswordConnect.ts index a90f5da2f42..b764467ec40 100644 --- a/src/standalone/userJupyterServer/jupyterPasswordConnect.ts +++ b/src/standalone/userJupyterServer/jupyterPasswordConnect.ts @@ -6,7 +6,7 @@ import { IConfigurationService, IDisposable, IDisposableRegistry } from '../../p import { DataScience } from '../../platform/common/utils/localize'; import { noop } from '../../platform/common/utils/misc'; import { InputFlowAction } from '../../platform/common/utils/multiStepInput'; -import { traceError, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { sendTelemetryEvent, Telemetry } from '../../telemetry'; import { IJupyterRequestAgentCreator, @@ -65,7 +65,7 @@ export class JupyterPasswordConnect { }).then((value) => { if (!value || (value.requiresPassword && Object.keys(value).length === 1)) { // If we fail to get a valid password connect info, don't save the value - traceWarning(`Password for ${newUrl} was invalid.`); + logger.warn(`Password for ${newUrl} was invalid.`); this.savedConnectInfo.delete(options.handle); } @@ -253,7 +253,7 @@ export class JupyterPasswordConnect { headers: { Connection: 'keep-alive' } }); if (response.status === 404) { - traceError(`Jupyter Server not found at ${url}, got 404 for ${treeUrl}`); + logger.error(`Jupyter Server not found at ${url}, got 404 for ${treeUrl}`); return false; } return response.status !== 200; diff --git a/src/standalone/userJupyterServer/serverSelectorForTests.ts b/src/standalone/userJupyterServer/serverSelectorForTests.ts index 06ed1aacdbd..cf2b73230e8 100644 --- a/src/standalone/userJupyterServer/serverSelectorForTests.ts +++ b/src/standalone/userJupyterServer/serverSelectorForTests.ts @@ -4,7 +4,7 @@ import { inject, injectable } from 'inversify'; import { CancellationToken, EventEmitter, Uri, commands } from 'vscode'; import { JVSC_EXTENSION_ID, TestingKernelPickerProviderId } from '../../platform/common/constants'; -import { traceInfo } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IJupyterServerProviderRegistry, IJupyterServerUriStorage } from '../../kernels/jupyter/types'; import { IExtensionSyncActivationService } from '../../platform/activation/types'; import { computeHash } from '../../platform/common/crypto'; @@ -50,7 +50,7 @@ export class JupyterServerSelectorCommand this._register(commands.registerCommand('jupyter.selectjupyteruri', this.selectJupyterUri, this)); } private async selectJupyterUri(source: Uri): Promise { - traceInfo(`Setting Jupyter Server URI to remote: ${source}`); + logger.info(`Setting Jupyter Server URI to remote: ${source}`); const uri = source.toString(true); const url = new URL(uri); const baseUrl = Uri.parse(`${url.protocol}//${url.host}${url.pathname === '/lab' ? '' : url.pathname}`); diff --git a/src/standalone/userJupyterServer/userServerUrlProvider.ts b/src/standalone/userJupyterServer/userServerUrlProvider.ts index 9a185e739d9..dc000498df2 100644 --- a/src/standalone/userJupyterServer/userServerUrlProvider.ts +++ b/src/standalone/userJupyterServer/userServerUrlProvider.ts @@ -49,7 +49,7 @@ import { } from '../../platform/common/types'; import { Common, DataScience } from '../../platform/common/utils/localize'; import { noop } from '../../platform/common/utils/misc'; -import { traceError, traceVerbose, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { JupyterPasswordConnect } from './jupyterPasswordConnect'; import { IJupyterServerUri, @@ -218,7 +218,7 @@ export class UserJupyterServerUrlProvider if (ex instanceof CancellationError) { throw ex; } - traceError(`Failed to select a Jupyter Server`, ex); + logger.error(`Failed to select a Jupyter Server`, ex); return; } finally { token.cancel(); @@ -508,7 +508,7 @@ export class UserJupyterServerUrlProvider true ); } catch (err) { - traceWarning('Uri verification error', err); + logger.warn('Uri verification error', err); // If we failed to verify the connection & we previously failed at capturing password, // Then go back to url with the same error message if (failedUrlPasswordCapture && validationErrorMessage) { @@ -688,7 +688,7 @@ export class UserJupyterServerUrlProvider serverUriToReturn.token = passwordResult.remappedToken; } } catch (ex) { - traceError(`Failed to validate Password info`, ex); + logger.error(`Failed to validate Password info`, ex); } return serverUriToReturn; @@ -799,7 +799,7 @@ export async function getBaseJupyterUrl(url: string, requestCreator: IJupyterReq return loginPage.substring(0, loginPage.indexOf('login?')); } } catch (ex) { - traceVerbose(`Unable to identify the baseUrl of the Jupyter Server`, ex); + logger.debug(`Unable to identify the baseUrl of the Jupyter Server`, ex); } } @@ -826,7 +826,7 @@ function sendRemoteTelemetryForAdditionOfNewRemoteServer( reason: failureReason }); }) - .catch((ex) => traceError(`Failed to hash remote url ${baseUrl}`, ex)); + .catch((ex) => logger.error(`Failed to hash remote url ${baseUrl}`, ex)); } export class UserJupyterServerDisplayName { @@ -928,7 +928,7 @@ export function parseUri(uri: string, displayName?: string): IJupyterServerUri | displayName: displayName || url.hostname }; } catch (err) { - traceError(`Failed to parse URI ${uri}`, err); + logger.error(`Failed to parse URI ${uri}`, err); // This should already have been parsed when set, so just throw if it's not right here return undefined; } diff --git a/src/standalone/variables/pythonVariableRequester.ts b/src/standalone/variables/pythonVariableRequester.ts index 5424fde4c80..4f77410c1af 100644 --- a/src/standalone/variables/pythonVariableRequester.ts +++ b/src/standalone/variables/pythonVariableRequester.ts @@ -4,7 +4,7 @@ import type * as nbformat from '@jupyterlab/nbformat'; import { inject, injectable } from 'inversify'; import { CancellationToken } from 'vscode'; -import { traceError, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { DataScience } from '../../platform/common/utils/localize'; import { stripAnsi } from '../../platform/common/utils/regexp'; import { JupyterDataRateLimitError } from '../../platform/errors/jupyterDataRateLimitError'; @@ -136,9 +136,7 @@ export class PythonVariablesRequester implements IKernelVariableRequester { return content?.summary; } catch (ex) { - traceWarning( - `Exception when getting variable summary for variable "${targetVariable.name}": ${ex.message}` - ); + logger.warn(`Exception when getting variable summary for variable "${targetVariable.name}": ${ex.message}`); return undefined; } } @@ -165,7 +163,7 @@ export class PythonVariablesRequester implements IKernelVariableRequester { try { return content; } catch (ex) { - traceError(ex); + logger.error(ex); return []; } } @@ -256,7 +254,7 @@ export class PythonVariablesRequester implements IKernelVariableRequester { throw new JupyterDataRateLimitError(); } else { const error = DataScience.jupyterGetVariablesExecutionError(resultString); - traceError(error); + logger.error(error); throw new Error(error); } } @@ -278,7 +276,7 @@ export class PythonVariablesRequester implements IKernelVariableRequester { const traceback: string[] = codeCellOutput.traceback as string[]; const stripped = traceback.map(stripAnsi).join('\r\n'); const error = DataScience.jupyterGetVariablesExecutionError(stripped); - traceError(error); + logger.error(error); throw new Error(error); } } diff --git a/src/test/client/api.vscode.test.ts b/src/test/client/api.vscode.test.ts index d45cb65ceee..6d5115d6653 100644 --- a/src/test/client/api.vscode.test.ts +++ b/src/test/client/api.vscode.test.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { assert } from 'chai'; -import { traceInfo } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IDisposable } from '../../platform/common/types'; import { closeNotebooksAndCleanUpAfterTests, startJupyterServer } from '../datascience/notebook/helper.node'; import { initialize } from '../initialize.node'; @@ -21,16 +21,16 @@ suite('3rd Party Kernel Service API @kernelCore', function () { this.timeout(120_000); let notebook: TestNotebookDocument; suiteSetup(async function () { - traceInfo('Suite Setup 3rd Party Kernel Service API'); + logger.info('Suite Setup 3rd Party Kernel Service API'); this.timeout(120_000); try { api = await initialize(); await startJupyterServer(); sinon.restore(); notebook = new TestNotebookDocument(); - traceInfo('Suite Setup (completed)'); + logger.info('Suite Setup (completed)'); } catch (e) { - traceInfo('Suite Setup (failed) - 3rd Party Kernel Service API'); + logger.info('Suite Setup (failed) - 3rd Party Kernel Service API'); await captureScreenShot('API-suite'); throw e; } @@ -58,12 +58,12 @@ suite('3rd Party Kernel Service API @kernelCore', function () { kernelProvider.getKernelExecution(kernel); sinon.restore(); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { sinon.restore(); await closeNotebooksAndCleanUpAfterTests(disposables); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); suiteTeardown(() => closeNotebooksAndCleanUpAfterTests(disposables)); diff --git a/src/test/datascience/data-viewing/showInDataViewerPythonInterpreter.vscode.test.ts b/src/test/datascience/data-viewing/showInDataViewerPythonInterpreter.vscode.test.ts index eecbbf4c2d3..69cc660b80f 100644 --- a/src/test/datascience/data-viewing/showInDataViewerPythonInterpreter.vscode.test.ts +++ b/src/test/datascience/data-viewing/showInDataViewerPythonInterpreter.vscode.test.ts @@ -5,7 +5,7 @@ import * as vscode from 'vscode'; import * as path from '../../../platform/vscode-path/path'; import * as sinon from 'sinon'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IDisposable } from '../../../platform/common/types'; import { captureScreenShot, openFile } from '../../common.node'; import { initialize } from '../../initialize.node'; @@ -29,12 +29,12 @@ suite('DataViewer @webview', function () { ); this.timeout(120_000); suiteSetup(async function () { - traceInfo('Suite Setup'); + logger.info('Suite Setup'); this.timeout(120_000); try { await initialize(); sinon.restore(); - traceInfo('Suite Setup (completed)'); + logger.info('Suite Setup (completed)'); } catch (e) { await captureScreenShot('data-viewer-suite'); throw e; diff --git a/src/test/datascience/debugger.vscode.test.ts b/src/test/datascience/debugger.vscode.test.ts index f4118113855..8cc8799a456 100644 --- a/src/test/datascience/debugger.vscode.test.ts +++ b/src/test/datascience/debugger.vscode.test.ts @@ -11,7 +11,7 @@ import { IControllerRegistration } from '../../notebooks/controllers/types'; import { IDebuggingManager, INotebookDebuggingManager } from '../../notebooks/debugger/debuggingTypes'; import { Commands, JVSC_EXTENSION_ID } from '../../platform/common/constants'; import { IDisposable } from '../../platform/common/types'; -import { traceError, traceInfo, traceVerbose } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import * as path from '../../platform/vscode-path/path'; import { IVariableViewProvider } from '../../webviews/extension-side/variablesView/types'; import { captureScreenShot, IExtensionTestApi, waitForCondition } from '../common.node'; @@ -41,7 +41,7 @@ suite('Run By Line @debugger', function () { let debuggingManager: IDebuggingManager; this.timeout(120_000); suiteSetup(async function () { - traceInfo(`Start Test Suite - Run By Line @debugger`); + logger.info(`Start Test Suite - Run By Line @debugger`); try { this.timeout(120_000); // Don't run if we can't use the native notebook interface @@ -50,32 +50,32 @@ suite('Run By Line @debugger', function () { } api = await initialize(); - traceVerbose('Step1'); + logger.debug('Step1'); await closeNotebooksAndCleanUpAfterTests(disposables); - traceVerbose('Step2'); + logger.debug('Step2'); await prewarmNotebooks(); - traceVerbose('Step3'); + logger.debug('Step3'); sinon.restore(); - traceVerbose('Step4'); + logger.debug('Step4'); const coreVariableViewProvider = api.serviceContainer.get(IVariableViewProvider); // eslint-disable-next-line @typescript-eslint/no-explicit-any - traceVerbose('Step5'); + logger.debug('Step5'); variableViewProvider = coreVariableViewProvider as any as ITestVariableViewProvider; // Cast to expose the test interfaces debuggingManager = api.serviceContainer.get(INotebookDebuggingManager); } catch (ex) { - traceError('Failed to setup suite for Run By Line @debugger', ex); + logger.error('Failed to setup suite for Run By Line @debugger', ex); throw ex; } finally { - traceInfo(`Start Test Suite (completed) - Run By Line @debugger`); + logger.info(`Start Test Suite (completed) - Run By Line @debugger`); } }); setup(async function () { this.timeout(120_000); - traceInfo(`Start Test (1) ${this.currentTest?.title}`); + logger.info(`Start Test (1) ${this.currentTest?.title}`); sinon.restore(); const metadata = await getDefaultKernelConnection(); const controllerRegistry = await api.serviceContainer.get(IControllerRegistration); - traceInfo(`Start Test (2) ${metadata.id}`); + logger.info(`Start Test (2) ${metadata.id}`); const controller = await waitForCondition( () => @@ -85,26 +85,26 @@ suite('Run By Line @debugger', function () { defaultNotebookTestTimeout, `Controller not found for connection ${metadata.id}` ); - traceInfo(`Start Test (3) ${controller.id}`); + logger.info(`Start Test (3) ${controller.id}`); await createEmptyPythonNotebook(disposables, undefined, true); - traceInfo(`Start Test (4) ${controller.id}`); + logger.info(`Start Test (4) ${controller.id}`); await commands.executeCommand('notebook.selectKernel', { id: controller!.id, extension: JVSC_EXTENSION_ID }); - traceInfo(`Start Test (5) ${controller.id}`); + logger.info(`Start Test (5) ${controller.id}`); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); if (this.currentTest?.isFailed()) { // For a flaky interrupt test. await captureScreenShot(this); } await closeNotebooks(disposables); await closeNotebooksAndCleanUpAfterTests(disposables); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); // Cleanup after suite is finished @@ -123,10 +123,10 @@ suite('Run By Line @debugger', function () { const cell = await insertCodeCell('a=1\na', { index: 0 }); const doc = window.activeNotebookEditor?.notebook!; - traceInfo(`Inserted cell`); + logger.info(`Inserted cell`); await commands.executeCommand(Commands.RunByLine, cell); - traceInfo(`Executed run by line`); + logger.info(`Executed run by line`); const { debugAdapter } = await getDebugSessionAndAdapter(debuggingManager, doc); // Make sure that we stop to dump the files @@ -161,10 +161,10 @@ suite('Run By Line @debugger', function () { // Run by line seems to end up on the second line of the function, not the first const cell = await insertCodeCell('a=1\na', { index: 0 }); const doc = window.activeNotebookEditor?.notebook!; - traceInfo(`Inserted cell`); + logger.info(`Inserted cell`); await commands.executeCommand(Commands.RunByLine, cell); - traceInfo(`Executed run by line`); + logger.info(`Executed run by line`); const { debugAdapter, session } = await getDebugSessionAndAdapter(debuggingManager, doc); const stoppedEvent = await waitForStoppedEvent(debugAdapter!); @@ -173,14 +173,14 @@ suite('Run By Line @debugger', function () { }); assert.isTrue(stack.stackFrames.length > 0, 'has frames'); assert.equal(stack.stackFrames[0].source?.path, cell.document.uri.toString(), 'Stopped at the wrong path'); - traceInfo(`Got past first stop event`); + logger.info(`Got past first stop event`); const coreVariableView = await variableViewProvider.activeVariableView; const variableView = coreVariableView as unknown as ITestWebviewHost; await commands.executeCommand(Commands.RunByLineNext, cell); await waitForStoppedEvent(debugAdapter!); - traceInfo(`Got past second stop event`); + logger.info(`Got past second stop event`); const expectedVariables = [{ name: 'a', type: 'int', length: '', value: '1' }]; await waitForVariablesToMatch(expectedVariables, variableView); @@ -196,7 +196,7 @@ suite('Run By Line @debugger', function () { defaultNotebookTestTimeout, 'Cell should have output' ); - traceInfo(`Got past third stop event`); + logger.info(`Got past third stop event`); assert.isTrue(getCellOutputs(cell).includes('1')); }); diff --git a/src/test/datascience/helpers.ts b/src/test/datascience/helpers.ts index 36dcb799b72..0839ccc1559 100644 --- a/src/test/datascience/helpers.ts +++ b/src/test/datascience/helpers.ts @@ -6,7 +6,7 @@ import { assert } from 'chai'; import * as vscode from 'vscode'; import { getFilePath } from '../../platform/common/platform/fs-paths'; -import { traceError, traceInfo, traceInfoIfCI, traceVerbose } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IPythonApiProvider } from '../../platform/api/types'; import { IJupyterSettings, Resource } from '../../platform/common/types'; import { InteractiveWindow } from '../../interactive-window/interactiveWindow'; @@ -31,10 +31,10 @@ import { isEqual } from '../../platform/vscode-path/resources'; import { instance } from 'ts-mockito'; export async function openNotebook(ipynbFile: vscode.Uri) { - traceInfo(`Opening notebook ${getFilePath(ipynbFile)}`); + logger.info(`Opening notebook ${getFilePath(ipynbFile)}`); const notebook = await vscode.workspace.openNotebookDocument(ipynbFile); const editor = await vscode.window.showNotebookDocument(notebook); - traceInfo(`Opened notebook ${getFilePath(ipynbFile)}`); + logger.info(`Opened notebook ${getFilePath(ipynbFile)}`); return { notebook, editor }; } @@ -83,7 +83,7 @@ export async function insertIntoInputEditor(source: string, interactiveWindow?: (e) => e.document.uri.path === interactiveWindow.inputUri.path ); if (!inputBox) { - traceError( + logger.error( `couldn't find input box ${interactiveWindow.inputUri.path} in visible text editors ${JSON.stringify( vscode.window.visibleTextEditors.map((e) => e.document.uri.path) )}` @@ -218,7 +218,7 @@ export async function waitForInteractiveWindow( let inputBox = vscode.window.visibleTextEditors.find( (e) => e.document.uri.path === interactiveWindow?.inputUri?.path ); - traceVerbose( + logger.debug( `Waiting for Interactive Window '${interactiveWindow.notebookUri?.toString()}',`, `found notebook '${notebookDocument?.uri.toString()}' and input '${inputBox?.document.uri.toString()}'` ); @@ -265,7 +265,7 @@ export async function waitForLastCellToComplete( } else { await waitForExecutionCompletedSuccessfully(codeCell!); } - traceInfoIfCI(`finished waiting for last cell to complete of ${codeCells.length} cells`); + logger.ci(`finished waiting for last cell to complete of ${codeCells.length} cells`); return codeCell!; } @@ -301,7 +301,7 @@ export async function waitForCodeLenses(document: vscode.Uri, command: string) { `Code lens with command ${command} not found` ); - traceInfoIfCI(`Found code lenses with command ${command}`); + logger.ci(`Found code lenses with command ${command}`); return codeLenses; } diff --git a/src/test/datascience/interactiveDebugging.vscode.common.ts b/src/test/datascience/interactiveDebugging.vscode.common.ts index d439681f669..be3ea3a5c96 100644 --- a/src/test/datascience/interactiveDebugging.vscode.common.ts +++ b/src/test/datascience/interactiveDebugging.vscode.common.ts @@ -4,7 +4,7 @@ import { assert } from 'chai'; import * as sinon from 'sinon'; import * as vscode from 'vscode'; -import { traceInfo } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { IDisposable } from '../../platform/common/types'; import { InteractiveWindowProvider } from '../../interactive-window/interactiveWindowProvider'; import { initialize, IExtensionTestApi, waitForCondition, startJupyterServer, captureScreenShot } from '../common'; @@ -60,7 +60,7 @@ export function sharedIWDebuggerTests( }); suiteTeardown(() => vscode.commands.executeCommand('workbench.debug.viewlet.action.removeAllBreakpoints')); setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); api = await initialize(); if (isWeb() || (IS_REMOTE_NATIVE_TEST() && debuggerType === 'VSCodePythonDebugger')) { await startJupyterServer(); @@ -75,13 +75,13 @@ export function sharedIWDebuggerTests( disposables.push(vscode.debug.registerDebugAdapterTrackerFactory('python', tracker)); disposables.push(vscode.debug.registerDebugAdapterTrackerFactory(pythonIWKernelDebugAdapter, tracker)); interactiveWindowProvider = api.serviceManager.get(IInteractiveWindowProvider); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); const coreVariableViewProvider = api.serviceContainer.get(IVariableViewProvider); // eslint-disable-next-line @typescript-eslint/no-explicit-any variableViewProvider = coreVariableViewProvider as any as ITestVariableViewProvider; // Cast to expose the test interfaces }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); if (this.currentTest?.isFailed()) { await captureScreenShot(this); } diff --git a/src/test/datascience/interactiveWindow.vscode.common.test.ts b/src/test/datascience/interactiveWindow.vscode.common.test.ts index 509ecb208b8..4185a5eb911 100644 --- a/src/test/datascience/interactiveWindow.vscode.common.test.ts +++ b/src/test/datascience/interactiveWindow.vscode.common.test.ts @@ -3,7 +3,7 @@ import { assert } from 'chai'; import * as vscode from 'vscode'; -import { traceInfo, traceInfoIfCI } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { getDisplayPath } from '../../platform/common/platform/fs-paths'; import { IDisposable, InteractiveWindowMode } from '../../platform/common/types'; import { InteractiveWindowProvider } from '../../interactive-window/interactiveWindowProvider'; @@ -62,16 +62,16 @@ suite(`Interactive window execution @iw`, async function () { const disposables: IDisposable[] = []; let interactiveWindowProvider: InteractiveWindowProvider; setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); api = await initialize(); if (IS_REMOTE_NATIVE_TEST()) { await startJupyterServer(); } interactiveWindowProvider = api.serviceManager.get(IInteractiveWindowProvider); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); if (this.currentTest?.isFailed()) { // For a flaky interrupt test. await captureScreenShot(this); @@ -80,7 +80,7 @@ suite(`Interactive window execution @iw`, async function () { // restore the default value const settings = vscode.workspace.getConfiguration('jupyter', null); await settings.update('interactiveWindow.creationMode', 'multiple'); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); test('__file__ exists even after restarting a kernel', async function () { // https://github.com/microsoft/vscode-jupyter/issues/12251 @@ -261,13 +261,13 @@ ${actualCode} `; - traceInfoIfCI('Before submitting'); + logger.ci('Before submitting'); const { activeInteractiveWindow: interactiveWindow } = await submitFromPythonFile( interactiveWindowProvider, codeWithWhitespace, disposables ); - traceInfoIfCI('After submitting'); + logger.ci('After submitting'); const lastCell = await waitForLastCellToComplete(interactiveWindow); const actualCellText = lastCell.document.getText(); assert.equal(actualCellText, dedentedCode); diff --git a/src/test/datascience/interactiveWindow.vscode.test.ts b/src/test/datascience/interactiveWindow.vscode.test.ts index 218751acc00..fb148c01140 100644 --- a/src/test/datascience/interactiveWindow.vscode.test.ts +++ b/src/test/datascience/interactiveWindow.vscode.test.ts @@ -4,7 +4,7 @@ import { assert } from 'chai'; import * as sinon from 'sinon'; import * as vscode from 'vscode'; -import { traceInfo } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { getDisplayPath, getFilePath } from '../../platform/common/platform/fs-paths'; import { IDisposable } from '../../platform/common/types'; import { InteractiveWindowProvider } from '../../interactive-window/interactiveWindowProvider'; @@ -52,17 +52,17 @@ suite(`Interactive window Execution @iw`, async function () { let pythonApiProvider: IPythonApiProvider; let originalActiveInterpreter: PythonEnvironment | undefined; setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); api = await initialize(); if (IS_REMOTE_NATIVE_TEST()) { await startJupyterServer(); } interactiveWindowProvider = api.serviceManager.get(IInteractiveWindowProvider); pythonApiProvider = api.serviceManager.get(IPythonApiProvider); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); await vscode.commands.executeCommand('python.clearWorkspaceInterpreter'); if (this.currentTest?.isFailed()) { // For a flaky interrupt test. diff --git a/src/test/datascience/interactiveWindowRemote.vscode.test.ts b/src/test/datascience/interactiveWindowRemote.vscode.test.ts index 6f90e9daf8a..94748539b3d 100644 --- a/src/test/datascience/interactiveWindowRemote.vscode.test.ts +++ b/src/test/datascience/interactiveWindowRemote.vscode.test.ts @@ -4,7 +4,7 @@ import { assert } from 'chai'; import { workspace, Disposable } from 'vscode'; import { IInteractiveWindowProvider } from '../../interactive-window/types'; -import { traceInfo } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { testMandatory } from '../common'; import { initialize, IS_REMOTE_NATIVE_TEST } from '../initialize.node'; import { submitFromPythonFile } from './helpers.node'; @@ -22,16 +22,16 @@ suite('Interactive window (remote) @iw', async () => { if (!IS_REMOTE_NATIVE_TEST()) { return this.skip(); } - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); const api = await initialize(); interactiveWindowProvider = api.serviceContainer.get(IInteractiveWindowProvider); await startJupyterServer(); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); await closeNotebooksAndCleanUpAfterTests(); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); suiteTeardown(() => closeNotebooksAndCleanUpAfterTests(disposables)); diff --git a/src/test/datascience/ipywidgets/ipyWidgetScriptManager.vscode.common.test.ts b/src/test/datascience/ipywidgets/ipyWidgetScriptManager.vscode.common.test.ts index 4b3ba0283ad..8e21e2c0dec 100644 --- a/src/test/datascience/ipywidgets/ipyWidgetScriptManager.vscode.common.test.ts +++ b/src/test/datascience/ipywidgets/ipyWidgetScriptManager.vscode.common.test.ts @@ -17,7 +17,7 @@ import { } from '../notebook/helper'; import { initialize } from '../../initialize'; import { JVSC_EXTENSION_ID, PYTHON_LANGUAGE } from '../../../platform/common/constants'; -import { traceTrace } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IKernel, IKernelProvider, isLocalConnection } from '../../../kernels/types'; import { getTelemetrySafeHashedString } from '../../../platform/telemetry/helpers'; import { IFileSystem } from '../../../platform/common/platform/types'; @@ -45,7 +45,7 @@ suite('IPyWidget Script Manager @widgets', function () { let fs: IFileSystem; let context: IExtensionContext; suiteSetup(async function () { - traceTrace('Suite Setup'); + logger.trace('Suite Setup'); api = await initialize(); await closeNotebooks(); await startJupyterServer(); @@ -97,18 +97,18 @@ suite('IPyWidget Script Manager @widgets', function () { kernel = kernelProvider.get(notebook)!; scriptManager = widgetScriptManagerFactory.getOrCreate(kernel); - traceTrace('Suite Setup (completed)'); + logger.trace('Suite Setup (completed)'); }); setup(async function () { - traceTrace(`Starting Test ${this.currentTest?.title}`); + logger.trace(`Starting Test ${this.currentTest?.title}`); }); teardown(async function () { - traceTrace(`Ended Test ${this.currentTest?.title}`); + logger.trace(`Ended Test ${this.currentTest?.title}`); if (this.currentTest?.isFailed()) { await captureScreenShot(this); } - traceTrace(`Ended Test (completed) ${this.currentTest?.title}`); + logger.trace(`Ended Test (completed) ${this.currentTest?.title}`); }); suiteTeardown(() => closeNotebooksAndCleanUpAfterTests(disposables)); test('Returns the right base Url', async function () { diff --git a/src/test/datascience/jupyter/connection.vscode.test.ts b/src/test/datascience/jupyter/connection.vscode.test.ts index 723203fa5f9..a5bced1c195 100644 --- a/src/test/datascience/jupyter/connection.vscode.test.ts +++ b/src/test/datascience/jupyter/connection.vscode.test.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { IEncryptedStorage } from '../../../platform/common/application/types'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IAsyncDisposableRegistry, IConfigurationService, @@ -149,7 +149,7 @@ suite('Connect to Remote Jupyter Servers @mandatory', function () { if (!IS_REMOTE_NATIVE_TEST()) { return this.skip(); } - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); const api = await initialize(); inputBox = { show: noop, @@ -216,14 +216,14 @@ suite('Connect to Remote Jupyter Servers @mandatory', function () { ); userUriProvider.activate(); - traceInfo(`Start Test Completed ${this.currentTest?.title}`); + logger.info(`Start Test Completed ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`End Test ${this.currentTest?.title}`); + logger.info(`End Test ${this.currentTest?.title}`); sinon.restore(); dispose(disposables); - traceInfo(`End Test Completed ${this.currentTest?.title}`); + logger.info(`End Test Completed ${this.currentTest?.title}`); }); suiteTeardown(() => closeNotebooksAndCleanUpAfterTests(disposables)); diff --git a/src/test/datascience/jupyterServer.node.ts b/src/test/datascience/jupyterServer.node.ts index 5070c0edd34..33b4fc342e1 100644 --- a/src/test/datascience/jupyterServer.node.ts +++ b/src/test/datascience/jupyterServer.node.ts @@ -274,11 +274,11 @@ export class JupyterServer { if (result.proc.pid) { this.pid = result.proc.pid; } - // result.proc.once('close', () => traceVerbose('Shutting Jupyter server used for remote tests (closed)')); + // result.proc.once('close', () => logger.debug('Shutting Jupyter server used for remote tests (closed)')); // result.proc.once('disconnect', () => - // traceVerbose('Shutting Jupyter server used for remote tests (disconnected)') + // logger.debug('Shutting Jupyter server used for remote tests (disconnected)') // ); - // result.proc.once('exit', () => traceVerbose('Shutting Jupyter server used for remote tests (exited)')); + // result.proc.once('exit', () => logger.debug('Shutting Jupyter server used for remote tests (exited)')); const procDisposable = { dispose: () => { if (!result.proc) { diff --git a/src/test/datascience/notebook/controllerDefaultService.ts b/src/test/datascience/notebook/controllerDefaultService.ts index 01bccb067c1..139a79f3121 100644 --- a/src/test/datascience/notebook/controllerDefaultService.ts +++ b/src/test/datascience/notebook/controllerDefaultService.ts @@ -13,7 +13,7 @@ import { import { IDisposableRegistry } from '../../../platform/common/types'; import { getNotebookMetadata } from '../../../platform/common/utils'; import { IInterpreterService } from '../../../platform/interpreter/contracts'; -import { traceInfoIfCI, traceDecoratorVerbose, traceError } from '../../../platform/logging'; +import { logger, debugDecorator } from '../../../platform/logging'; import { createActiveInterpreterController } from './helpers'; import { IControllerRegistration, IVSCodeNotebookController } from '../../../notebooks/controllers/types'; import { IServiceContainer } from '../../../platform/ioc/types'; @@ -46,10 +46,10 @@ export class ControllerDefaultService { viewType: typeof JupyterNotebookView | typeof InteractiveWindowView ): Promise { if (!IS_REMOTE_NATIVE_TEST() && this.interpreters) { - traceInfoIfCI('CreateActiveInterpreterController'); + logger.ci('CreateActiveInterpreterController'); return createActiveInterpreterController(viewType, notebook?.uri, this.interpreters, this.registration); } else { - traceInfoIfCI('CreateDefaultRemoteController'); + logger.ci('CreateDefaultRemoteController'); const controller = await this.createDefaultRemoteController(viewType, notebook); // If we're running on web, there is no active interpreter to fall back to if (controller || isWebExtension()) { @@ -60,7 +60,7 @@ export class ControllerDefaultService { } } - @traceDecoratorVerbose('Get default Remote Controller') + @debugDecorator('Get default Remote Controller') private async createDefaultRemoteController( notebookType: typeof JupyterNotebookView | typeof InteractiveWindowView, notebook?: NotebookDocument @@ -100,7 +100,7 @@ export class ControllerDefaultService { return true; }); if (controllers.length === 0) { - traceError('No remote controllers'); + logger.error('No remote controllers'); return; } diff --git a/src/test/datascience/notebook/controllerPreferredService.ts b/src/test/datascience/notebook/controllerPreferredService.ts index 52c988b8b50..17443ccd9b9 100644 --- a/src/test/datascience/notebook/controllerPreferredService.ts +++ b/src/test/datascience/notebook/controllerPreferredService.ts @@ -33,14 +33,7 @@ import { IDisposable, IDisposableRegistry } from '../../../platform/common/types import { getNotebookMetadata, getResourceType, isJupyterNotebook } from '../../../platform/common/utils'; import { noop } from '../../../platform/common/utils/misc'; import { IInterpreterService } from '../../../platform/interpreter/contracts'; -import { - logValue, - traceDecoratorVerbose, - traceError, - traceInfo, - traceInfoIfCI, - traceVerbose -} from '../../../platform/logging'; +import { logValue, debugDecorator, logger } from '../../../platform/logging'; import { PythonEnvironment } from '../../../platform/pythonEnvironments/info'; import { sendTelemetryEvent } from '../../../telemetry'; import { IServiceContainer } from '../../../platform/ioc/types'; @@ -109,7 +102,7 @@ export class ControllerPreferredService { public dispose() { dispose(Array.from(this.disposables)); } - @traceDecoratorVerbose('Compute Preferred Controller') + @debugDecorator('Compute Preferred Controller') public async computePreferred( @logValue('uri') document: NotebookDocument, cancelToken?: CancellationToken @@ -121,7 +114,7 @@ export class ControllerPreferredService { return {}; } - traceInfoIfCI(`Clear controller mapping for ${getDisplayPath(document.uri)}`); + logger.ci(`Clear controller mapping for ${getDisplayPath(document.uri)}`); // Keep track of a token per document so that we can cancel the search if the doc is closed this.preferredCancelTokens.get(document)?.cancel(); this.preferredCancelTokens.get(document)?.dispose(); @@ -159,7 +152,7 @@ export class ControllerPreferredService { } preferredConnection = defaultPythonController?.connection; if (preferredConnection) { - traceInfoIfCI( + logger.ci( `Found target controller with default controller ${getDisplayPath(document.uri)} ${ preferredConnection.kind }:${preferredConnection.id}.` @@ -167,12 +160,12 @@ export class ControllerPreferredService { } } if (preferredSearchToken.token.isCancellationRequested) { - traceInfoIfCI(`Fetching TargetController document ${getDisplayPath(document.uri)} cancelled.`); + logger.ci(`Fetching TargetController document ${getDisplayPath(document.uri)} cancelled.`); return {}; } if (document.notebookType === JupyterNotebookView && !preferredConnection) { if (preferredSearchToken.token.isCancellationRequested) { - traceInfoIfCI(`Fetching TargetController document ${getDisplayPath(document.uri)} cancelled.`); + logger.ci(`Fetching TargetController document ${getDisplayPath(document.uri)} cancelled.`); return {}; } @@ -184,14 +177,14 @@ export class ControllerPreferredService { undefined ); if (preferredConnection) { - traceInfoIfCI( + logger.ci( `Found target controller with an exact match (1) ${getDisplayPath(document.uri)} ${ preferredConnection.kind }:${preferredConnection.id}.` ); } if (preferredSearchToken.token.isCancellationRequested) { - traceInfoIfCI(`Fetching TargetController document ${getDisplayPath(document.uri)} cancelled.`); + logger.ci(`Fetching TargetController document ${getDisplayPath(document.uri)} cancelled.`); return {}; } // If we didn't find an exact match in the cache, try awaiting for the non-cache version @@ -204,7 +197,7 @@ export class ControllerPreferredService { undefined ); if (preferredConnection) { - traceInfoIfCI( + logger.ci( `Found target controller with an exact match (2) ${getDisplayPath(document.uri)} ${ preferredConnection.kind }:${preferredConnection.id}.` @@ -212,24 +205,22 @@ export class ControllerPreferredService { } } if (preferredSearchToken.token.isCancellationRequested) { - traceInfoIfCI(`Fetching TargetController document ${getDisplayPath(document.uri)} cancelled.`); + logger.ci(`Fetching TargetController document ${getDisplayPath(document.uri)} cancelled.`); return {}; } // If we found a preferred kernel, set the association on the NotebookController if (preferredSearchToken.token.isCancellationRequested && !preferredConnection) { - traceVerbose('Find preferred kernel cancelled'); + logger.debug('Find preferred kernel cancelled'); return {}; } if (!preferredConnection) { - traceInfoIfCI( - `PreferredConnection not found for NotebookDocument: ${getDisplayPath(document.uri)}` - ); + logger.ci(`PreferredConnection not found for NotebookDocument: ${getDisplayPath(document.uri)}`); if (!preferredConnection && this.preferredControllers.get(document)) { // Possible previously we had just 1 controller and that was setup as the preferred // & now that we have more controllers, we know more about what needs to be matched // & since we no longer have a preferred, we should probably unset the previous preferred - traceVerbose( + logger.debug( `Resetting the previous preferred controller ${this.preferredControllers.get(document) ?.id} to default affinity for document ${getDisplayPath(document.uri)}` ); @@ -241,7 +232,7 @@ export class ControllerPreferredService { return {}; } - traceInfo( + logger.info( `PreferredConnection: ${preferredConnection.id} found for NotebookDocument: ${getDisplayPath( document.uri )}` @@ -253,7 +244,7 @@ export class ControllerPreferredService { // If the controller doesn't exist, then it means we're still loading them. // However we can create this one as we have all of the necessary info. if (!targetController) { - traceVerbose(`Early registration of controller for Kernel connection ${preferredConnection.id}`); + logger.debug(`Early registration of controller for Kernel connection ${preferredConnection.id}`); // eslint-disable-next-line @typescript-eslint/no-explicit-any this.registration.addOrUpdate(preferredConnection, [JupyterNotebookView]); } @@ -262,7 +253,7 @@ export class ControllerPreferredService { // can happen if a document is opened quick and we have not yet loaded our controllers await this.registration.loaded; if (preferredSearchToken.token.isCancellationRequested) { - traceInfoIfCI(`Fetching TargetController document ${getDisplayPath(document.uri)} cancelled.`); + logger.ci(`Fetching TargetController document ${getDisplayPath(document.uri)} cancelled.`); return {}; } @@ -273,7 +264,7 @@ export class ControllerPreferredService { ); preferredConnection = defaultInteractiveController?.connection; if (preferredSearchToken.token.isCancellationRequested) { - traceInfoIfCI(`Fetching TargetController document ${getDisplayPath(document.uri)} cancelled.`); + logger.ci(`Fetching TargetController document ${getDisplayPath(document.uri)} cancelled.`); return {}; } } @@ -286,7 +277,7 @@ export class ControllerPreferredService { } if (targetController) { - traceVerbose( + logger.debug( `TargetController found ID: ${targetController.connection.kind}:${ targetController.id } for document ${getDisplayPath(document.uri)}` @@ -300,7 +291,7 @@ export class ControllerPreferredService { NotebookControllerAffinity.Preferred ); if (preferredSearchToken.token.isCancellationRequested) { - traceInfoIfCI(`Fetching TargetController document ${getDisplayPath(document.uri)} cancelled.`); + logger.ci(`Fetching TargetController document ${getDisplayPath(document.uri)} cancelled.`); return {}; } @@ -310,7 +301,7 @@ export class ControllerPreferredService { }); if (preferredSearchToken.token.isCancellationRequested) { - traceInfoIfCI(`Fetching TargetController document ${getDisplayPath(document.uri)} cancelled.`); + logger.ci(`Fetching TargetController document ${getDisplayPath(document.uri)} cancelled.`); return {}; } @@ -320,7 +311,7 @@ export class ControllerPreferredService { // Possible previously we had just 1 controller and that was setup as the preferred // & now that we have more controllers, we know more about what needs to be matched // & since we no longer have a preferred, we should probably unset the previous preferred - traceVerbose( + logger.debug( `Resetting the previous preferred controller ${this.preferredControllers.get(document) ?.id} to default affinity for document ${getDisplayPath(document.uri)}` ); @@ -336,7 +327,7 @@ export class ControllerPreferredService { const controller = this.registration.addOrUpdate(preferredConnection, [ document.notebookType as typeof JupyterNotebookView | typeof InteractiveWindowView ]); - traceInfoIfCI( + logger.ci( `Controller for preferred connection ${preferredConnection.kind}${ preferredConnection.id } for notebook ${getDisplayPath(document.uri)} does not yet exist, creating this now` @@ -344,14 +335,14 @@ export class ControllerPreferredService { if (controller.length === 1) { targetController = controller[0]; } else { - traceError( + logger.error( `Failed to create the controller for preferred connection ${preferredConnection.kind}${ preferredConnection.id } for notebook ${getDisplayPath(document.uri)}` ); } } - traceInfoIfCI( + logger.ci( `TargetController found ID: ${preferredConnection?.id} type ${preferredConnection?.kind} for document ${getDisplayPath( document.uri )} & associated controller id ${targetController?.connection?.kind}:${targetController?.id}` @@ -359,7 +350,7 @@ export class ControllerPreferredService { return { preferredConnection, controller: targetController }; } catch (ex) { - traceError('Failed to find & set preferred controllers', ex); + logger.error('Failed to find & set preferred controllers', ex); return {}; } finally { if (changeHandler) { @@ -484,7 +475,7 @@ export class ControllerPreferredService { isExactMatch || isNonPythonLanguageMatch ) { - traceInfo( + logger.info( `Preferred kernel ${potentialMatch.id} is exact match or top match for non python kernels, (${onlyConnection}, ${topMatchIsPreferredInterpreter}, ${isExactMatch}, ${isNonPythonLanguageMatch})` ); preferredConnection = potentialMatch; diff --git a/src/test/datascience/notebook/diagnosticProvider.vscode.test.ts b/src/test/datascience/notebook/diagnosticProvider.vscode.test.ts index 2fb3e577a99..2742df7434a 100644 --- a/src/test/datascience/notebook/diagnosticProvider.vscode.test.ts +++ b/src/test/datascience/notebook/diagnosticProvider.vscode.test.ts @@ -4,7 +4,7 @@ /* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires */ import { assert } from 'chai'; import { DataScience } from '../../../platform/common/utils/localize'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IDisposable } from '../../../platform/common/types'; import { captureScreenShot, IExtensionTestApi, waitForCondition } from '../../common.node'; import { initialize } from '../../initialize.node'; @@ -21,7 +21,7 @@ suite('VSCode Notebook -', function () { let activeNotebook: NotebookDocument; setup(async function () { try { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); api = await initialize(); diagnosticProvider = api.serviceContainer .getAll(IExtensionSyncActivationService) @@ -29,16 +29,16 @@ suite('VSCode Notebook -', function () { await createEmptyPythonNotebook(disposables); activeNotebook = window.activeNotebookEditor!.notebook; assert.isOk(activeNotebook, 'No active notebook'); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); } catch (e) { await captureScreenShot(this); throw e; } }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); await closeNotebooksAndCleanUpAfterTests(disposables); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); test('Show error for pip install', async () => { await insertCodeCell('!pip install xyz', { index: 0 }); diff --git a/src/test/datascience/notebook/executionService.mock.vscode.test.ts b/src/test/datascience/notebook/executionService.mock.vscode.test.ts index 029818da27b..aaee62fa9e3 100644 --- a/src/test/datascience/notebook/executionService.mock.vscode.test.ts +++ b/src/test/datascience/notebook/executionService.mock.vscode.test.ts @@ -7,7 +7,7 @@ // import * as sinon from 'sinon'; // import { Common } from '../../../platform/common/utils/localize'; // import { IVSCodeNotebook } from '../../../platform/common/application/types'; -// import { traceInfo } from '../../../platform/common/logger.node'; +// import { logger } from '../../../platform/common/logger.node'; // import { IDisposable, Product } from '../../../platform/common/types'; // import { IExtensionTestApi } from '../../common'; // import { initialize } from '../../initialize'; @@ -58,7 +58,7 @@ // let notebookProvider: INotebookProvider; // suiteSetup(async function () { // return this.skip(); -// traceInfo('Suite Setup'); +// logger.info('Suite Setup'); // this.timeout(120_000); // api = await initialize(); // if (!(await canRunNotebookTests())) { @@ -77,23 +77,23 @@ // vscodeNotebook = api.serviceContainer.get(IVSCodeNotebook); // controllerManager = api.serviceContainer.get(INotebookControllerManager); // notebookProvider = api.serviceContainer.get(INotebookProvider); -// traceInfo('Suite Setup (completed)'); +// logger.info('Suite Setup (completed)'); // }); // // Use same notebook without starting kernel in every single test (use one for whole suite). // setup(async function () { -// traceInfo(`Start Test ${this.currentTest?.title}`); +// logger.info(`Start Test ${this.currentTest?.title}`); // sinon.restore(); // await startJupyterServer(); // await createEmptyPythonNotebook(disposables); // assert.isOk(vscodeNotebook.activeNotebookEditor, 'No active notebook'); -// traceInfo(`Start Test (completed) ${this.currentTest?.title}`); +// logger.info(`Start Test (completed) ${this.currentTest?.title}`); // }); // teardown(async function () { -// traceInfo(`Ended Test ${this.currentTest?.title}`); +// logger.info(`Ended Test ${this.currentTest?.title}`); // // Added temporarily to identify why tests are failing. // process.env.VSC_JUPYTER_LOG_KERNEL_OUTPUT = undefined; // await closeNotebooksAndCleanUpAfterTests(disposables); -// traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); +// logger.info(`Ended Test (completed) ${this.currentTest?.title}`); // }); // suiteTeardown(() => closeNotebooksAndCleanUpAfterTests(disposables)); // function createKernelWithMockJupyterSession(notebook: NotebookDocument, session: IJupyterKernelConnectionSession) { diff --git a/src/test/datascience/notebook/executionService.vscode.test.ts b/src/test/datascience/notebook/executionService.vscode.test.ts index eb7fa425d7a..0eae540f5e1 100644 --- a/src/test/datascience/notebook/executionService.vscode.test.ts +++ b/src/test/datascience/notebook/executionService.vscode.test.ts @@ -22,7 +22,7 @@ import { WorkspaceEdit } from 'vscode'; import { Common } from '../../../platform/common/utils/localize'; -import { traceError, traceInfo, traceVerbose } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IDisposable } from '../../../platform/common/types'; import { captureScreenShot, IExtensionTestApi, waitForCondition, testMandatory } from '../../common.node'; import { EXTENSION_ROOT_DIR_FOR_TESTS, initialize } from '../../initialize.node'; @@ -88,7 +88,7 @@ suite('Kernel Execution @kernelCore', function () { if (getOSType() === OSType.Windows && isCI) { return this.skip(); } - traceInfo('Suite Setup VS Code Notebook - Execution'); + logger.info('Suite Setup VS Code Notebook - Execution'); this.timeout(120_000); try { api = await initialize(); @@ -103,39 +103,39 @@ suite('Kernel Execution @kernelCore', function () { .getConfiguration('python', workspace.workspaceFolders![0].uri) .update('envFile', '${workspaceFolder}/.env'); } - traceVerbose('Before starting Jupyter'); + logger.debug('Before starting Jupyter'); await startJupyterServer(); - traceVerbose('After starting Jupyter'); + logger.debug('After starting Jupyter'); sinon.restore(); notebook = new TestNotebookDocument(templateNbPath); const kernelProvider = api.serviceContainer.get(IKernelProvider); - traceVerbose('Before creating kernel connection'); + logger.debug('Before creating kernel connection'); const metadata = await getDefaultKernelConnection(); - traceVerbose('After creating kernel connection'); + logger.debug('After creating kernel connection'); const controller = createKernelController(); kernel = kernelProvider.getOrCreate(notebook, { metadata, resourceUri: notebook.uri, controller }); - traceVerbose('Before starting kernel'); + logger.debug('Before starting kernel'); await kernel.start(); - traceVerbose('After starting kernel'); + logger.debug('After starting kernel'); kernelExecution = kernelProvider.getKernelExecution(kernel); - traceInfo('Suite Setup (completed)'); + logger.info('Suite Setup (completed)'); } catch (e) { - traceError('Suite Setup (failed) - Execution', e); + logger.error('Suite Setup (failed) - Execution', e); await captureScreenShot('execution-suite'); throw e; } }); setup(function () { notebook.cells.length = 0; - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { if (this.currentTest?.isFailed()) { // For a flaky interrupt test. await captureScreenShot(this); } - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); suiteTeardown(() => closeNotebooksAndCleanUpAfterTests(disposables)); testMandatory('Execute cell using VSCode Kernel', async () => { @@ -593,8 +593,8 @@ suite('Kernel Execution @kernelCore', function () { sys.stderr.flush() ` ); - traceInfo('1. Start execution for test of Stderr & stdout outputs'); - traceInfo('2. Start execution for test of Stderr & stdout outputs'); + logger.info('1. Start execution for test of Stderr & stdout outputs'); + logger.info('2. Start execution for test of Stderr & stdout outputs'); await Promise.all([ kernelExecution.executeCell(cell), waitForTextOutput(cell, '1', 0, false), @@ -602,7 +602,7 @@ suite('Kernel Execution @kernelCore', function () { waitForTextOutput(cell, '3', 2, false), waitForTextOutput(cell, 'c', 3, false) ]); - traceInfo('2. completed execution for test of Stderr & stdout outputs'); + logger.info('2. completed execution for test of Stderr & stdout outputs'); // In cell 1 we should have the output // 12 diff --git a/src/test/datascience/notebook/exportFull.vscode.test.ts b/src/test/datascience/notebook/exportFull.vscode.test.ts index 7cb3fb86ae9..bb9d86a7e36 100644 --- a/src/test/datascience/notebook/exportFull.vscode.test.ts +++ b/src/test/datascience/notebook/exportFull.vscode.test.ts @@ -8,7 +8,7 @@ import * as os from 'os'; import * as path from '../../../platform/vscode-path/path'; import * as sinon from 'sinon'; import { Common, DataScience } from '../../../platform/common/utils/localize'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IConfigurationService, IDisposable } from '../../../platform/common/types'; import { captureScreenShot, IExtensionTestApi, PYTHON_PATH } from '../../common.node'; import { initialize } from '../../initialize.node'; @@ -51,7 +51,7 @@ suite('Export @export', function () { let template: string; this.timeout(120_000); suiteSetup(async function () { - traceInfo('Suite Setup'); + logger.info('Suite Setup'); this.timeout(120_000); try { api = await initialize(); @@ -69,7 +69,7 @@ suite('Export @export', function () { sinon.restore(); proc = new ProcessService(); - traceInfo('Suite Setup (completed)'); + logger.info('Suite Setup (completed)'); } catch (e) { await captureScreenShot('export-suite'); throw e; @@ -82,12 +82,12 @@ suite('Export @export', function () { // Use same notebook without starting kernel in every single test (use one for whole suite). setup(async function () { try { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); sinon.restore(); await startJupyterServer(); await createEmptyPythonNotebook(disposables); assert.isOk(window.activeNotebookEditor, 'No active notebook'); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); activeInterpreter = (await interpreterService.getActiveInterpreter( window.activeNotebookEditor?.notebook.uri ))!; @@ -104,7 +104,7 @@ suite('Export @export', function () { } }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); if (this.currentTest?.isFailed()) { await captureScreenShot(this); } @@ -113,7 +113,7 @@ suite('Export @export', function () { await settings.update('pythonExportMethod', 'direct', ConfigurationTarget.Global); await closeNotebooksAndCleanUpAfterTests(disposables); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); suiteTeardown(() => closeNotebooksAndCleanUpAfterTests(disposables)); test('Export a basic notebook document', async () => { diff --git a/src/test/datascience/notebook/helper.ts b/src/test/datascience/notebook/helper.ts index 0df1d62a4b3..ca493ad56fb 100644 --- a/src/test/datascience/notebook/helper.ts +++ b/src/test/datascience/notebook/helper.ts @@ -87,7 +87,7 @@ import { DataScience } from '../../../platform/common/utils/localize'; import { isWeb } from '../../../platform/common/utils/misc'; import { openAndShowNotebook } from '../../../platform/common/utils/notebooks'; import { IInterpreterService } from '../../../platform/interpreter/contracts'; -import { traceInfo, traceInfoIfCI, traceVerbose, traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { areInterpreterPathsSame } from '../../../platform/pythonEnvironments/info/interpreter'; import * as urlPath from '../../../platform/vscode-path/resources'; import { initialize, waitForCondition } from '../../common'; @@ -284,7 +284,7 @@ export async function createEmptyPythonNotebook( rootFolder?: Uri, dontWaitForKernel?: boolean ) { - traceInfoIfCI('Creating an empty notebook'); + logger.ci('Creating an empty notebook'); await getServices(); // Don't use same file (due to dirty handling, we might save in dirty.) // Coz we won't save to file, hence extension will backup in dirty file and when u re-open it will open from dirty. @@ -305,12 +305,12 @@ export async function createEmptyPythonNotebook( } await deleteAllCellsAndWait(); const notebook = window.activeNotebookEditor!.notebook; - traceVerbose(`Empty notebook created ${getDisplayPath(notebook.uri)}`); + logger.debug(`Empty notebook created ${getDisplayPath(notebook.uri)}`); return { notebook, editor: window.activeNotebookEditor! }; } async function shutdownAllNotebooks() { - traceVerbose('Shutting down all kernels'); + logger.debug('Shutting down all kernels'); const api = await initialize(); const kernelProvider = api.serviceContainer.get(IKernelProvider) as IKernelProvider; await Promise.all(kernelProvider.kernels.map((k) => k.dispose().catch(noop))); @@ -383,7 +383,7 @@ export async function closeNotebooks(disposables: IDisposable[] = []) { if (!isInsiders()) { return false; } - traceVerbose( + logger.debug( `Before Closing all notebooks, currently opened ${workspace.notebookDocuments .map((item) => getDisplayPath(item.uri)) .join(', ')}` @@ -406,13 +406,13 @@ export async function closeNotebooks(disposables: IDisposable[] = []) { dispose(disposables); await shutdownAllNotebooks(); if (workspace.notebookDocuments.length) { - traceVerbose( + logger.debug( `After Closing all notebooks, currently opened ${workspace.notebookDocuments .map((item) => getDisplayPath(item.uri)) .join(', ')}` ); } else { - traceVerbose(`Closed all notebooks`); + logger.debug(`Closed all notebooks`); } } @@ -474,13 +474,13 @@ async function waitForKernelToChangeImpl( ); if (controller) { // eslint-disable-next-line local-rules/dont-use-fspath - traceVerbose(`Did match a controller that matches the interpreter ${interpreterPath.fsPath}`); + logger.debug(`Did match a controller that matches the interpreter ${interpreterPath.fsPath}`); } else { // eslint-disable-next-line local-rules/dont-use-fspath - traceWarning(`Did not find a controller that matches the interpreter ${interpreterPath.fsPath}`); + logger.warn(`Did not find a controller that matches the interpreter ${interpreterPath.fsPath}`); } } - traceInfo( + logger.info( `Switching to kernel id ${controller?.id}, current controllers ${controllerRegistration.all .map( (c) => @@ -499,10 +499,10 @@ async function waitForKernelToChangeImpl( return false; } if (selectedController.id === controller?.id) { - traceInfo(`Found selected kernel id:label ${selectedController.id}:${selectedController.label}`); + logger.info(`Found selected kernel id:label ${selectedController.id}:${selectedController.label}`); return true; } - traceInfo(`Active kernel is id:label = ${selectedController.id}:${selectedController.label}`); + logger.info(`Active kernel is id:label = ${selectedController.id}:${selectedController.label}`); return false; }; if (!(await isRightKernel())) { @@ -514,7 +514,7 @@ async function waitForKernelToChangeImpl( if (!(await isRightKernel()) && !skipAutoSelection) { const criteria = typeof searchCriteria === 'function' ? await searchCriteria() : searchCriteria; lastCriteria = JSON.stringify(lastCriteria); - traceInfoIfCI( + logger.ci( `Notebook select.kernel command switching to kernel id ${controller?.connection .kind}${controller?.id}: Try ${tryCount} for ${JSON.stringify(criteria)}` ); @@ -523,7 +523,7 @@ async function waitForKernelToChangeImpl( id: controller?.id, extension: JVSC_EXTENSION_ID }); - traceInfoIfCI( + logger.ci( `Notebook select.kernel command switched to kernel id ${controller?.connection.kind}:${controller?.id}` ); tryCount += 1; @@ -537,7 +537,7 @@ async function waitForKernelToChangeImpl( ); // Make sure the kernel is actually in use before returning (switching is async) await sleep(500); - traceInfoIfCI( + logger.ci( `Notebook select.kernel command successfully switched to kernel id ${controller?.connection.kind}${controller?.id}: after ${tryCount} attempts.` ); } @@ -734,14 +734,14 @@ export async function waitForKernelToGetAutoSelectedImpl( timeout = 100_000, skipAutoSelection: boolean = false ) { - traceInfoIfCI('Wait for kernel to get auto selected'); + logger.ci('Wait for kernel to get auto selected'); const { controllerRegistration, controllerPreferred, interpreterService } = await getServices(); const useRemoteKernelSpec = IS_REMOTE_NATIVE_TEST() || isWebExtension(); // Web is only remote // Wait for the active editor to come up notebookEditor = await waitForActiveNotebookEditor(notebookEditor); - traceInfoIfCI(`Wait for kernel - got notebook controllers`); + logger.ci(`Wait for kernel - got notebook controllers`); const notebookControllers = controllerRegistration.registered; // Make sure we don't already have a selection (this function gets run even after opening a document) @@ -757,9 +757,9 @@ export async function waitForKernelToGetAutoSelectedImpl( await controllerPreferred.computePreferred(notebookEditor!.notebook); preferred = controllerPreferred.getPreferred(notebookEditor!.notebook); if (!preferred) { - traceInfoIfCI(`Did not find a controller with document affinity`); + logger.ci(`Did not find a controller with document affinity`); } - traceInfoIfCI( + logger.ci( `Wait for kernel - got a preferred notebook controller: ${preferred?.connection.kind}:${preferred?.id}` ); @@ -780,7 +780,7 @@ export async function waitForKernelToGetAutoSelectedImpl( } } if (!match) { - traceInfoIfCI(`Manually pick a preferred kernel from all kernel specs`); + logger.ci(`Manually pick a preferred kernel from all kernel specs`); const matches = notebookControllers.filter( (d) => d.connection.kind != 'connectToLiveRemoteKernel' && @@ -789,10 +789,8 @@ export async function waitForKernelToGetAutoSelectedImpl( ); const activeInterpreter = await interpreterService?.getActiveInterpreter(notebookEditor!.notebook.uri); - traceInfoIfCI( - `Attempt to find a kernel that matches the active interpreter ${activeInterpreter?.uri.path}` - ); - traceInfoIfCI( + logger.ci(`Attempt to find a kernel that matches the active interpreter ${activeInterpreter?.uri.path}`); + logger.ci( `Matches: ${matches .map((m) => m.connection.kind + ', ' + m.connection.interpreter?.uri.path) .join('\n ')}` @@ -809,7 +807,7 @@ export async function waitForKernelToGetAutoSelectedImpl( } if (!match) { - traceInfoIfCI( + logger.ci( `Houston, we have a problem, no match. Expected language ${expectedLanguage}. Expected kind ${preferredKind}.` ); assert.fail( @@ -820,7 +818,7 @@ export async function waitForKernelToGetAutoSelectedImpl( } const criteria = { labelOrId: match!.id }; - traceInfo( + logger.info( `Preferred kernel for selection is ${match.connection.kind}:${match?.id}, criteria = ${JSON.stringify( criteria )}` @@ -850,7 +848,7 @@ export async function prewarmNotebooks() { await insertCodeCell('print("Hello World1")', { index: 0 }); await selectDefaultController(notebookEditor, defaultNotebookTestTimeout); const cell = window.activeNotebookEditor!.notebook.cellAt(0)!; - traceInfoIfCI(`Running all cells in prewarm notebooks`); + logger.ci(`Running all cells in prewarm notebooks`); await Promise.all([waitForExecutionCompletedSuccessfully(cell, 60_000), runAllCellsInActiveNotebook()]); await closeActiveWindows(); await shutdownAllNotebooks(); @@ -1168,7 +1166,7 @@ function hasTextOutputValue(output: NotebookCellOutputItem, value: string, isExa ? haystack === value || haystack.trim() === value : haystack.toLowerCase().includes(value.toLowerCase()); } catch (ex) { - traceInfoIfCI(`Looking for value ${value}, but failed with error`, ex); + logger.ci(`Looking for value ${value}, but failed with error`, ex); return false; } } @@ -1313,14 +1311,14 @@ export async function hijackPrompt( let displayCount = 0; // eslint-disable-next-line const stub = sinon.stub(window, promptType).callsFake(function (msg: string) { - traceInfo(`Message displayed to user '${msg}', condition ${JSON.stringify(message)}`); + logger.info(`Message displayed to user '${msg}', condition ${JSON.stringify(message)}`); if ( ('exactMatch' in message && msg.trim() === message.exactMatch.trim()) || ('contains' in message && msg.trim().includes(message.contains.trim())) || ('endsWith' in message && msg.endsWith(message.endsWith)) ) { messageDisplayed.push(msg); - traceInfo(`Exact Message found '${msg}'`); + logger.info(`Exact Message found '${msg}'`); displayCount += 1; displayed.resolve(true); if (buttonToClick) { @@ -1369,10 +1367,10 @@ export async function hijackSavePrompt( const messageDisplayed: string[] = []; let displayCount = 0; const showSaveDialogFake = (msg: { saveLabel: string }) => { - traceInfo(`Message displayed to user '${JSON.stringify(msg)}', checking for '${saveLabel}'`); + logger.info(`Message displayed to user '${JSON.stringify(msg)}', checking for '${saveLabel}'`); if (msg.saveLabel === saveLabel) { messageDisplayed.push(msg.saveLabel); - traceInfo(`Exact Message found '${msg.saveLabel}'`); + logger.info(`Exact Message found '${msg.saveLabel}'`); displayCount += 1; displayed.resolve(true); if (buttonToClick) { @@ -1572,9 +1570,9 @@ export async function clickOKForRestartPrompt() { await initialize(); // Ensure we click `Yes` when prompted to restart the kernel. const showInformationMessage = sinon.stub(window, 'showInformationMessage').callsFake(function (message: string) { - traceInfo(`Step 2. ShowInformationMessage ${message}`); + logger.info(`Step 2. ShowInformationMessage ${message}`); if (message === DataScience.restartKernelMessage) { - traceInfo(`Step 3. ShowInformationMessage & yes to restart`); + logger.info(`Step 3. ShowInformationMessage & yes to restart`); // User clicked ok to restart it. return DataScience.restartKernelMessageYes; } diff --git a/src/test/datascience/notebook/helpers.ts b/src/test/datascience/notebook/helpers.ts index efc8fcb9b6f..971815cff2b 100644 --- a/src/test/datascience/notebook/helpers.ts +++ b/src/test/datascience/notebook/helpers.ts @@ -7,7 +7,7 @@ import { JupyterNotebookView, InteractiveWindowView } from '../../../platform/co import { getDisplayPath } from '../../../platform/common/platform/fs-paths'; import { Resource } from '../../../platform/common/types'; import { IInterpreterService } from '../../../platform/interpreter/contracts'; -import { traceInfoIfCI } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IControllerRegistration, IVSCodeNotebookController } from '../../../notebooks/controllers/types'; // This is here so the default service and the loader service can both use it without having @@ -31,7 +31,7 @@ export async function createActiveInterpreterController( const controllers = registration.addOrUpdate(metadata, [viewType]); const controller = controllers[0]; // Should only create one because only one view type registration.trackActiveInterpreterControllers(controllers); - traceInfoIfCI( + logger.ci( `Active Interpreter Controller ${controller.connection.kind}:${ controller.id } created for View ${viewType} with resource ${getDisplayPath(resource)}` diff --git a/src/test/datascience/notebook/intellisense/completion.vscode.common.test.ts b/src/test/datascience/notebook/intellisense/completion.vscode.common.test.ts index 87624f52b05..0ea782264f6 100644 --- a/src/test/datascience/notebook/intellisense/completion.vscode.common.test.ts +++ b/src/test/datascience/notebook/intellisense/completion.vscode.common.test.ts @@ -5,7 +5,7 @@ import { assert } from 'chai'; import * as sinon from 'sinon'; import { commands, CompletionList, Position, window } from 'vscode'; -import { traceInfo } from '../../../../platform/logging'; +import { logger } from '../../../../platform/logging'; import { IDisposable } from '../../../../platform/common/types'; import { closeNotebooksAndCleanUpAfterTests, @@ -23,29 +23,29 @@ suite('VSCode Intellisense Notebook and Interactive Code Completion @lsp', funct const disposables: IDisposable[] = []; this.timeout(120_000); suiteSetup(async function () { - traceInfo(`Start Suite Code Completion via Jupyter`); + logger.info(`Start Suite Code Completion via Jupyter`); this.timeout(120_000); await initialize(); await startJupyterServer(); await prewarmNotebooks(); sinon.restore(); - traceInfo(`Start Suite (Completed) Code Completion via Jupyter`); + logger.info(`Start Suite (Completed) Code Completion via Jupyter`); }); // Use same notebook without starting kernel in every single test (use one for whole suite). setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); sinon.restore(); await startJupyterServer(); await createEmptyPythonNotebook(disposables); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); if (this.currentTest?.isFailed()) { await captureScreenShot(this); } await closeNotebooksAndCleanUpAfterTests(disposables); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); suiteTeardown(() => closeNotebooksAndCleanUpAfterTests(disposables)); test('Execute cell and get completions for variable', async () => { @@ -57,12 +57,12 @@ suite('VSCode Intellisense Notebook and Interactive Code Completion @lsp', funct // Wait till execution count changes and status is success. await waitForExecutionCompletedSuccessfully(cell); const outputText = getTextOutputValue(cell.outputs[0]).trim(); - traceInfo(`Cell Output ${outputText}`); + logger.info(`Cell Output ${outputText}`); await insertCodeCell('a.', { index: 1 }); const cell2 = window.activeNotebookEditor!.notebook.cellAt(1); const position = new Position(0, 2); - traceInfo('Get completions in test'); + logger.info('Get completions in test'); // Executing the command `vscode.executeCompletionItemProvider` to simulate triggering completion const completions = (await commands.executeCommand( 'vscode.executeCompletionItemProvider', diff --git a/src/test/datascience/notebook/intellisense/completionProvider.vscode.common.test.ts b/src/test/datascience/notebook/intellisense/completionProvider.vscode.common.test.ts index 8f87439a1b5..fc79bf92a7b 100644 --- a/src/test/datascience/notebook/intellisense/completionProvider.vscode.common.test.ts +++ b/src/test/datascience/notebook/intellisense/completionProvider.vscode.common.test.ts @@ -6,7 +6,7 @@ import { assert } from 'chai'; import * as path from '../../../../platform/vscode-path/path'; import * as sinon from 'sinon'; import { ConfigurationTarget, Position, window, workspace, WorkspaceConfiguration, WorkspaceEdit } from 'vscode'; -import { traceInfo } from '../../../../platform/logging'; +import { logger } from '../../../../platform/logging'; import { IDisposable } from '../../../../platform/common/types'; import { IS_REMOTE_NATIVE_TEST } from '../../../constants'; import { @@ -41,7 +41,7 @@ import { IKernelProvider } from '../../../../kernels/types'; if (IS_REMOTE_NATIVE_TEST()) { return this.skip(); } - traceInfo(`Start Suite Code Completion via Jupyter`); + logger.info(`Start Suite Code Completion via Jupyter`); this.timeout(120_000); jupyterConfig = workspace.getConfiguration('jupyter', undefined); previousJediSetting = jupyterConfig.get('enableExtendedPythonKernelCompletions'); @@ -56,21 +56,21 @@ import { IKernelProvider } from '../../../../kernels/types'; sinon.restore(); kernelCompletionProviderRegistry = api.serviceContainer.get(KernelCompletionProvider); - traceInfo(`Start Suite (Completed) Code Completion via Jupyter`); + logger.info(`Start Suite (Completed) Code Completion via Jupyter`); }); // Use same notebook without starting kernel in every single test (use one for whole suite). setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); sinon.restore(); await startJupyterServer(); await createEmptyPythonNotebook(disposables, undefined, true); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { sinon.restore(); - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); await closeNotebooksAndCleanUpAfterTests(disposables); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); suiteTeardown(async () => { await jupyterConfig.update( @@ -112,7 +112,7 @@ import { IKernelProvider } from '../../../../kernels/types'; // Wait till execution count changes and status is success. await waitForExecutionCompletedSuccessfully(cell2); - traceInfo(`last cell output: ${getCellOutputs(cell2)}`); + logger.info(`last cell output: ${getCellOutputs(cell2)}`); // Now add the cell to check intellisense. await insertCodeCell(cellCode); @@ -122,7 +122,7 @@ import { IKernelProvider } from '../../../../kernels/types'; 0, cellCode.includes('"') || cellCode.includes("'") ? cellCode.length - 1 : cellCode.length ); - traceInfo('Get completions in test'); + logger.info('Get completions in test'); const kernel = api.serviceContainer .get(IKernelProvider) .get(window.activeNotebookEditor!.notebook)!; diff --git a/src/test/datascience/notebook/interruptRestart.vscode.test.ts b/src/test/datascience/notebook/interruptRestart.vscode.test.ts index 37b40f9059c..5fb38bcfe3b 100644 --- a/src/test/datascience/notebook/interruptRestart.vscode.test.ts +++ b/src/test/datascience/notebook/interruptRestart.vscode.test.ts @@ -4,7 +4,7 @@ import { assert } from 'chai'; import * as sinon from 'sinon'; import { window } from 'vscode'; -import { traceError, traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IConfigurationService, IDisposable, IJupyterSettings, ReadWrite } from '../../../platform/common/types'; import { noop } from '../../../platform/common/utils/misc'; import { IKernel, IKernelProvider, INotebookKernelExecution } from '../../../kernels/types'; @@ -47,38 +47,38 @@ suite('Restart/Interrupt/Cancel/Errors @kernelCore', function () { let previousTestFailed: boolean | undefined = false; async function initSuite() { try { - traceInfo(`Start Suite Test Restart/Interrupt/Cancel/Errors @kernelCore`); + logger.info(`Start Suite Test Restart/Interrupt/Cancel/Errors @kernelCore`); await startJupyterServer(); await closeNotebooksAndCleanUpAfterTests(); notebook = new TestNotebookDocument(); const kernelProvider = api.serviceContainer.get(IKernelProvider); const metadata = await getDefaultKernelConnection(); - traceInfo(`Start Suite Test Restart/Interrupt/Cancel/Errors @kernelCore metadata ${metadata.id}`); + logger.info(`Start Suite Test Restart/Interrupt/Cancel/Errors @kernelCore metadata ${metadata.id}`); const controller = createKernelController(); - traceInfo(`Controller created`); + logger.info(`Controller created`); kernel = kernelProvider.getOrCreate(notebook, { metadata, resourceUri: notebook.uri, controller }); - traceInfo(`Kernel created`); + logger.info(`Kernel created`); await kernel.start(); - traceInfo(`Kernel started`); + logger.info(`Kernel started`); kernelExecution = kernelProvider.getKernelExecution(kernel); - traceInfo(`Start Suite Test Complete Restart/Interrupt/Cancel/Errors @kernelCore`); + logger.info(`Start Suite Test Complete Restart/Interrupt/Cancel/Errors @kernelCore`); } catch (ex) { - traceError('Suite Setup (failed) - Test Restart/Interrupt/Cancel/Errors @kernelCore', ex); + logger.error('Suite Setup (failed) - Test Restart/Interrupt/Cancel/Errors @kernelCore', ex); await captureScreenShot('execution-suite'); throw ex; } } suiteSetup(async function () { - traceInfo(`Start Suite Test Restart/Interrupt/Cancel/Errors @kernelCore`); + logger.info(`Start Suite Test Restart/Interrupt/Cancel/Errors @kernelCore`); api = await initialize(); dsSettings = api.serviceContainer.get(IConfigurationService).getSettings(undefined); oldAskForRestart = dsSettings.askForKernelRestart; await initSuite(); }); setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); if (previousTestFailed) { - traceInfo(`Start Running Test Suite again for ${this.currentTest?.title}`); + logger.info(`Start Running Test Suite again for ${this.currentTest?.title}`); await closeNotebooksAndCleanUpAfterTests(disposables.concat(suiteDisposables)); await initSuite(); } @@ -86,11 +86,11 @@ suite('Restart/Interrupt/Cancel/Errors @kernelCore', function () { notebook.cells.length = 0; // Disable the prompt (when attempting to restart kernel). dsSettings.askForKernelRestart = false; - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(function () { previousTestFailed = this.currentTest?.isFailed(); - traceInfo(`End Test (completed) ${this.currentTest?.title}`); + logger.info(`End Test (completed) ${this.currentTest?.title}`); }); suiteTeardown(async () => { if (dsSettings) { @@ -106,16 +106,16 @@ suite('Restart/Interrupt/Cancel/Errors @kernelCore', function () { const showInformationMessage = sinon.stub(window, 'showInformationMessage'); showInformationMessage.resolves(); // Ignore message to restart kernel. disposables.push({ dispose: () => showInformationMessage.restore() }); - traceInfo('Step 1'); + logger.info('Step 1'); const execPromise = kernelExecution.executeCell(cell).catch(noop); - traceInfo('Step 2'); + logger.info('Step 2'); await waitForTextOutput(cell, '1', 0, false); - traceInfo('Step 3'); + logger.info('Step 3'); // Interrupt the kernel. const interruptPromise = kernel.interrupt().catch(noop); - traceInfo('Step 4'); + logger.info('Step 4'); // Wait for interruption (cell will fail with errors). await Promise.all([ @@ -123,84 +123,84 @@ suite('Restart/Interrupt/Cancel/Errors @kernelCore', function () { interruptPromise, waitForCondition(async () => hasErrorOutput(cell.outputs), 30_000, 'No errors') ]); - traceInfo('Step 5'); + logger.info('Step 5'); }); test('Restarting kernel will cancel cell execution & we can re-run a cell', async function () { if (IS_REMOTE_NATIVE_TEST()) { return this.skip(); } - traceInfo('Step 1'); + logger.info('Step 1'); const cell = await notebook.appendCodeCell( 'import time\nfor i in range(10000):\n print(i)\n time.sleep(0.1)' ); // Ensure we click `Yes` when prompted to restart the kernel. disposables.push(await clickOKForRestartPrompt()); - traceInfo(`Step 4. Before execute`); - traceInfo(`Step 5. After execute`); + logger.info(`Step 4. Before execute`); + logger.info(`Step 5. After execute`); const promise = kernelExecution.executeCell(cell).catch(noop); await waitForTextOutput(cell, '1', 0, false); // Restart the kernel & use event handler to check if it was restarted successfully. const waitForKernelToRestart = createEventHandler(kernel, 'onRestarted', disposables); - traceInfo('Step 9 Wait for restart'); + logger.info('Step 9 Wait for restart'); kernel.restart().catch(noop); // Wait for kernel to restart before we execute cells again. await waitForKernelToRestart.assertFired(30_000); - traceInfo('Step 10 Restarted'); + logger.info('Step 10 Restarted'); // Wait for cell completed await waitForCondition( async () => NotebookCellStateTracker.getCellState(cell) === NotebookCellExecutionState.Idle, 60_000, 'Cell did not stop running' ); - traceInfo('Step 11 Restarted'); + logger.info('Step 11 Restarted'); // Clear the cells // Clear the outputs. cell.outputs.length = 0; // Confirm we can execute a cell (using the new kernel session). - traceInfo('Step 12 Executed'); + logger.info('Step 12 Executed'); kernelExecution.executeCell(cell).catch(noop); await waitForTextOutput(cell, '1', 0, false); - traceInfo(`Step 13. Cell output`); + logger.info(`Step 13. Cell output`); // Don't have to wait for interrupt, as sometimes interrupt can timeout & we get a prompt to restart. // Stop execution of the cell (if possible) in kernel. kernel.interrupt().catch(noop); // Stop the cell (cleaner way to tear down this test, else VS Code can hang due to the fact that we delete/close notebooks & rest of the code is trying to access it). - traceInfo('Step 14'); + logger.info('Step 14'); // Wait for interruption (cell will fail with errors). await Promise.all([promise, waitForCondition(async () => hasErrorOutput(cell.outputs), 30_000, 'No errors')]); - traceInfo('Step 15'); + logger.info('Step 15'); }); test('Restarting kernel during run all will skip the rest of the cells', async function () { - traceInfo('Step 1'); + logger.info('Step 1'); await notebook.appendCodeCell('print(1)'); const cell = await notebook.appendCodeCell('import time\nprint(2)\ntime.sleep(60)'); const lastCell = await notebook.appendCodeCell('print(3)'); // Ensure we click `Yes` when prompted to restart the kernel. await clickOKForRestartPrompt(); - traceInfo(`Step 4. Before execute`); - traceInfo(`Step 5. After execute`); + logger.info(`Step 4. Before execute`); + logger.info(`Step 5. After execute`); const executionPromise = Promise.all( notebook.cells.map((cell) => kernelExecution.executeCell(cell).catch(noop)) ); await waitForTextOutput(cell, '2', 0, false); - traceInfo(`Step 6. Cell is busy`); + logger.info(`Step 6. Cell is busy`); // Restart the kernel & use event handler to check if it was restarted successfully. const waitForKernelToRestart = createEventHandler(kernel, 'onRestarted', disposables); const restartPromise = kernel.restart().catch(noop); // Wait for kernel to restart before we execute cells again. - traceInfo('Step 8 Wait for restart'); + logger.info('Step 8 Wait for restart'); await waitForKernelToRestart.assertFired(30_000); - traceInfo('Step 9 Restarted'); + logger.info('Step 9 Restarted'); // Confirm last cell is empty await Promise.all([executionPromise, restartPromise]); @@ -385,13 +385,13 @@ suite('Restart/Interrupt/Cancel/Errors @kernelCore', function () { // Restart the kernel & use event handler to check if it was restarted successfully. const waitForKernelToRestart = createEventHandler(kernel, 'onRestarted', disposables); - traceInfo('Step 9 Wait for restart'); + logger.info('Step 9 Wait for restart'); await Promise.all([ kernel.restart(), // Wait for kernel to restart before we execute cells again. waitForKernelToRestart.assertFired(30_000) ]); - traceInfo('Step 10 Restarted'); + logger.info('Step 10 Restarted'); // Run the first cell again & this time it should work. // When we re-run the cells, the execution order shoulld start from 1 all over again diff --git a/src/test/datascience/notebook/kernelCrashes.vscode.test.ts b/src/test/datascience/notebook/kernelCrashes.vscode.test.ts index e1cbf60f1cf..9dab8ee4db3 100644 --- a/src/test/datascience/notebook/kernelCrashes.vscode.test.ts +++ b/src/test/datascience/notebook/kernelCrashes.vscode.test.ts @@ -5,7 +5,7 @@ import { assert } from 'chai'; import * as sinon from 'sinon'; import { DataScience } from '../../../platform/common/utils/localize'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IConfigurationService, IDisposable, IExtensionContext } from '../../../platform/common/types'; import { captureScreenShot, IExtensionTestApi, waitForCondition } from '../../common.node'; import { initialize } from '../../initialize.node'; @@ -62,7 +62,7 @@ suite('VSCode Notebook Kernel Error Handling - @kernelCore', function () { ) => void | Thenable; let controller: NotebookController; suiteSetup(async function () { - traceInfo('Suite Setup'); + logger.info('Suite Setup'); this.timeout(120_000); try { api = await initialize(); @@ -126,7 +126,7 @@ suite('VSCode Notebook Kernel Error Handling - @kernelCore', function () { ); disposables.push(interpreterController); - traceInfo('Suite Setup (completed)'); + logger.info('Suite Setup (completed)'); } catch (e) { await captureScreenShot('execution-suite'); throw e; @@ -135,24 +135,24 @@ suite('VSCode Notebook Kernel Error Handling - @kernelCore', function () { // Use same notebook without starting kernel in every single test (use one for whole suite). setup(async function () { try { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); sinon.restore(); await startJupyterServer(); notebook = new TestNotebookDocument(); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); } catch (e) { await captureScreenShot(this); throw e; } }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); if (this.currentTest?.isFailed()) { await captureScreenShot(this); } await closeNotebooksAndCleanUpAfterTests(disposables); sinon.restore(); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); suiteTeardown(() => { sinon.restore(); diff --git a/src/test/datascience/notebook/kernelRankingHelper.ts b/src/test/datascience/notebook/kernelRankingHelper.ts index d98dbf6b911..341d7c61149 100644 --- a/src/test/datascience/notebook/kernelRankingHelper.ts +++ b/src/test/datascience/notebook/kernelRankingHelper.ts @@ -17,7 +17,7 @@ import { IJupyterKernelSpec, KernelConnectionMetadata, PythonKernelConnectionMet import { InteractiveWindowView, isCI, PYTHON_LANGUAGE } from '../../../platform/common/constants'; import { getDisplayPath } from '../../../platform/common/platform/fs-paths'; import { NotebookMetadata } from '../../../platform/common/utils'; -import { traceError, traceInfo, traceInfoIfCI } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { PythonEnvironment } from '../../../platform/pythonEnvironments/info'; import { getInterpreterHash } from '../../../platform/pythonEnvironments/info/interpreter'; import * as path from '../../../platform/vscode-path/path'; @@ -66,7 +66,7 @@ export async function findKernelSpecMatchingInterpreter( // if we have more than one match then something is wrong. if (result.length > 1) { - traceError(`More than one kernel spec matches the interpreter ${interpreter.uri}.`, result); + logger.error(`More than one kernel spec matches the interpreter ${interpreter.uri}.`, result); if (isCI) { throw new Error('More than one kernelspec matches the intererpreter'); } @@ -98,7 +98,7 @@ export async function rankKernels( preferredRemoteKernelId: string | undefined, cancelToken?: CancellationToken ): Promise { - traceInfo( + logger.info( `Find preferred kernel for ${getDisplayPath(notebook.uri)} with metadata ${JSON.stringify( notebookMetadata || {} )} & preferred interpreter ${ @@ -129,7 +129,7 @@ export async function rankKernels( kernels.push(preferredInterpreterKernelSpec); } - traceInfoIfCI(`preferredInterpreterKernelSpecIndex = ${preferredInterpreterKernelSpec?.id}`); + logger.ci(`preferredInterpreterKernelSpecIndex = ${preferredInterpreterKernelSpec?.id}`); // Figure out our possible language from the metadata const actualNbMetadataLanguage: string | undefined = @@ -999,7 +999,7 @@ export class KernelRankingHelper { return rankedKernels; } catch (ex) { - traceError(`RankKernels crashed`, ex); + logger.error(`RankKernels crashed`, ex); return undefined; } } diff --git a/src/test/datascience/notebook/nonPythonKernels.vscode.test.ts b/src/test/datascience/notebook/nonPythonKernels.vscode.test.ts index 523b4f348b8..2809bcc4288 100644 --- a/src/test/datascience/notebook/nonPythonKernels.vscode.test.ts +++ b/src/test/datascience/notebook/nonPythonKernels.vscode.test.ts @@ -8,7 +8,7 @@ import { Uri } from 'vscode'; import { IKernelProvider } from '../../../kernels/types'; import { PythonExtensionChecker } from '../../../platform/api/pythonApi'; import { IDisposable } from '../../../platform/common/types'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import * as path from '../../../platform/vscode-path/path'; import { IExtensionTestApi, waitForCondition } from '../../common.node'; import { EXTENSION_ROOT_DIR_FOR_TESTS, IS_NON_RAW_NATIVE_TEST, IS_REMOTE_NATIVE_TEST } from '../../constants.node'; @@ -59,13 +59,13 @@ suite('Non-Python Kernel @nonPython ', async function () { ); } setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); sinon.restore(); await closeNotebooks(); // Don't use same file (due to dirty handling, we might save in dirty.) // Coz we won't save to file, hence extension will backup in dirty file and when u re-open it will open from dirty. testDenoNb = await createTemporaryNotebookFromFile(denoNb, disposables); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async () => { verifyPromptWasNotDisplayed(); diff --git a/src/test/datascience/notebook/outputDisplayOrder.vscode.test.ts b/src/test/datascience/notebook/outputDisplayOrder.vscode.test.ts index 61730334f17..e9942fa43c4 100644 --- a/src/test/datascience/notebook/outputDisplayOrder.vscode.test.ts +++ b/src/test/datascience/notebook/outputDisplayOrder.vscode.test.ts @@ -4,7 +4,7 @@ /* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires */ import * as path from '../../../platform/vscode-path/path'; import { assert } from 'chai'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { EXTENSION_ROOT_DIR_FOR_TESTS } from '../../constants.node'; import { closeNotebooksAndCleanUpAfterTests } from './helper.node'; import { Uri, workspace } from 'vscode'; @@ -26,12 +26,12 @@ suite('Validate Output order', function () { await initialize(); }); setup(async function () { - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); await closeNotebooksAndCleanUpAfterTests(); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); suiteTeardown(() => closeNotebooksAndCleanUpAfterTests()); test('Verify order of outputs in existing ipynb file', async () => { diff --git a/src/test/datascience/notebook/remote.vscode.common.test.ts b/src/test/datascience/notebook/remote.vscode.common.test.ts index 898d97562dd..b7105e89e39 100644 --- a/src/test/datascience/notebook/remote.vscode.common.test.ts +++ b/src/test/datascience/notebook/remote.vscode.common.test.ts @@ -11,7 +11,7 @@ import { workspace, WorkspaceEdit } from 'vscode'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IDisposable } from '../../../platform/common/types'; import { captureScreenShot, startJupyterServer, suiteMandatory, testMandatory, waitForCondition } from '../../common'; import { initialize } from '../../initialize'; @@ -37,31 +37,31 @@ suiteMandatory('Remote Tests', function () { if (!isWeb()) { return this.skip(); } - traceInfo('Suite Setup Remote Tests'); + logger.info('Suite Setup Remote Tests'); this.timeout(120_000); await initialize(); - traceInfo('Suite Setup Remote Tests, Step 2'); + logger.info('Suite Setup Remote Tests, Step 2'); await startJupyterServer(); - traceInfo('Suite Setup Remote Tests, Step 4'); + logger.info('Suite Setup Remote Tests, Step 4'); await prewarmNotebooks(); - traceInfo('Suite Setup Remote Tests, Step 5'); + logger.info('Suite Setup Remote Tests, Step 5'); editor = (await createEmptyPythonNotebook(disposables, undefined, true)).editor; await selectDefaultController(editor); - traceInfo('Suite Setup (completed)'); + logger.info('Suite Setup (completed)'); }); // Use same notebook without starting kernel in every single test (use one for whole suite). setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); await startJupyterServer(); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); if (this.currentTest?.isFailed()) { await captureScreenShot(this); } // await closeNotebooksAndCleanUpAfterTests(disposables); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); suiteTeardown(async () => closeNotebooksAndCleanUpAfterTests(disposables)); testMandatory('Execute cell and print Hello World', async function () { diff --git a/src/test/datascience/notebook/remoteNotebookEditor.vscode.common.test.ts b/src/test/datascience/notebook/remoteNotebookEditor.vscode.common.test.ts index 48e70d39212..57e8426d1c8 100644 --- a/src/test/datascience/notebook/remoteNotebookEditor.vscode.common.test.ts +++ b/src/test/datascience/notebook/remoteNotebookEditor.vscode.common.test.ts @@ -5,7 +5,7 @@ import { assert } from 'chai'; import * as sinon from 'sinon'; import { commands, CompletionList, Position, Uri, window } from 'vscode'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IDisposable } from '../../../platform/common/types'; import { captureScreenShot, IExtensionTestApi, initialize, startJupyterServer, waitForCondition } from '../../common'; import { closeActiveWindows } from '../../initialize'; @@ -58,7 +58,7 @@ suite('Remote Execution @kernelCore', function () { }); // Use same notebook without starting kernel in every single test (use one for whole suite). setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); sinon.restore(); if (!this.currentTest?.title.includes('preferred')) { await startJupyterServer(); @@ -83,15 +83,15 @@ suite('Remote Execution @kernelCore', function () { ], disposables ); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); if (this.currentTest?.isFailed()) { await captureScreenShot(this); } await closeNotebooksAndCleanUpAfterTests(disposables); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); suiteTeardown(() => closeNotebooksAndCleanUpAfterTests(disposables)); test('MRU and encrypted storage should be updated with remote Uri info', async function () { diff --git a/src/test/datascience/notebook/remoteNotebookEditor.vscode.test.ts b/src/test/datascience/notebook/remoteNotebookEditor.vscode.test.ts index b009f42ac5c..c8fa3476c79 100644 --- a/src/test/datascience/notebook/remoteNotebookEditor.vscode.test.ts +++ b/src/test/datascience/notebook/remoteNotebookEditor.vscode.test.ts @@ -7,7 +7,7 @@ import { assert } from 'chai'; import * as sinon from 'sinon'; import { commands, Uri, window } from 'vscode'; import { PYTHON_LANGUAGE } from '../../../platform/common/constants'; -import { traceInfoIfCI, traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { captureScreenShot, IExtensionTestApi, initialize, waitForCondition } from '../../common'; import { openNotebook } from '../helpers'; import { closeNotebooksAndCleanUpAfterTests } from './helper'; @@ -54,7 +54,7 @@ suite('Remote Kernel Execution', function () { }); // Use same notebook without starting kernel in every single test (use one for whole suite). setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); sinon.restore(); if (!this.currentTest?.title.includes('preferred')) { await startJupyterServer(); @@ -79,24 +79,24 @@ suite('Remote Kernel Execution', function () { ], disposables ); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); if (this.currentTest?.isFailed()) { await captureScreenShot(this); } await closeNotebooksAndCleanUpAfterTests(disposables); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); suiteTeardown(() => closeNotebooksAndCleanUpAfterTests(disposables)); test('Local Kernel state is not lost when connecting to remote', async function () { const activeInterpreter = await interpreterService.getActiveInterpreter(); - traceInfoIfCI(`active interpreter ${activeInterpreter?.uri.path}`); + logger.ci(`active interpreter ${activeInterpreter?.uri.path}`); const { notebook } = await createEmptyPythonNotebook(disposables); const controllerManager = svcContainer.get(IControllerRegistration); const preferredController = controllerManager.getSelected(notebook); - traceInfoIfCI(`preferred controller ${preferredController?.connection.id}`); + logger.ci(`preferred controller ${preferredController?.connection.id}`); await insertCodeCell('a = "123412341234"', { index: 0 }); await insertCodeCell('print(a)', { index: 1 }); @@ -111,8 +111,8 @@ suite('Remote Kernel Execution', function () { await waitForCondition( async () => { const controllers = controllerRegistration.registered; - traceInfoIfCI(`Check ${controllers.length} registered controllers`); - traceInfoIfCI( + logger.ci(`Check ${controllers.length} registered controllers`); + logger.ci( `list controllers ${controllers.length}: ${controllers .map((i) => `${i.connection.id}, ${i.connection.kind}`) .join('\n')}` @@ -124,7 +124,7 @@ suite('Remote Kernel Execution', function () { ); const newPreferredController = controllerManager.getSelected(notebook); - traceInfoIfCI(`new preferred controller ${newPreferredController?.connection.id}`); + logger.ci(`new preferred controller ${newPreferredController?.connection.id}`); // Run the second cell and verify we still have the same kernel state. await Promise.all([runCell(cell2), waitForTextOutput(cell2, '123412341234')]); diff --git a/src/test/datascience/notebook/stackTraceParsing.vscode.test.ts b/src/test/datascience/notebook/stackTraceParsing.vscode.test.ts index fba95797576..91bcf72a674 100644 --- a/src/test/datascience/notebook/stackTraceParsing.vscode.test.ts +++ b/src/test/datascience/notebook/stackTraceParsing.vscode.test.ts @@ -4,7 +4,7 @@ import { assert } from 'chai'; import { findErrorLocation } from '../../../kernels/execution/helpers'; import { closeNotebooksAndCleanUpAfterTests, createEmptyPythonNotebook, insertCodeCell } from './helper'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { window } from 'vscode'; import sinon from 'sinon'; import { IDisposable } from '../../../platform/common/types'; @@ -15,20 +15,20 @@ suite('StackTraceParsing', () => { setup(async function () { this.timeout(120_000); - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); sinon.restore(); await createEmptyPythonNotebook(disposables, undefined, true); assert.isOk(window.activeNotebookEditor, 'No active notebook'); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); if (this.currentTest?.isFailed()) { await captureScreenShot(this); } await closeNotebooksAndCleanUpAfterTests(disposables); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); test('Correct range is identified for raw stack strace', async () => { diff --git a/src/test/datascience/plotViewer/plotViewer.vscode.test.ts b/src/test/datascience/plotViewer/plotViewer.vscode.test.ts index cd27b295254..68994675ee1 100644 --- a/src/test/datascience/plotViewer/plotViewer.vscode.test.ts +++ b/src/test/datascience/plotViewer/plotViewer.vscode.test.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { assert } from 'chai'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IDisposable } from '../../../platform/common/types'; import { waitForCondition } from '../../common.node'; import { closeActiveWindows, initialize } from '../../initialize.node'; @@ -28,17 +28,17 @@ suite('VSCode Notebook PlotViewer integration - VSCode Notebook @webview', funct }); setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); - traceInfo(`Start Test Completed ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test Completed ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`End Test ${this.currentTest?.title}`); + logger.info(`End Test ${this.currentTest?.title}`); if (this.currentTest?.isFailed()) { await captureScreenShot(this); } await closeNotebooksAndCleanUpAfterTests(disposables); - traceInfo(`End Test Completed ${this.currentTest?.title}`); + logger.info(`End Test Completed ${this.currentTest?.title}`); }); suiteTeardown(() => closeNotebooksAndCleanUpAfterTests(disposables)); @@ -68,7 +68,7 @@ plt.show()`, await waitForCondition(async () => plotCell?.outputs.length >= 1, 10000, 'Plot output not generated'); // Sometimes on CI we end up with >1 output, and the test fails, but we're expecting just one. if (plotCell.outputs.length === 0) { - traceInfo(`Plot cell has ${plotCell.outputs.length} outputs`); + logger.info(`Plot cell has ${plotCell.outputs.length} outputs`); } assert.isAtLeast(plotCell.outputs.length, 1, 'Plot cell output incorrect count'); diff --git a/src/test/datascience/variableView/variableView.vscode.test.ts b/src/test/datascience/variableView/variableView.vscode.test.ts index c685d68b213..6367d06949c 100644 --- a/src/test/datascience/variableView/variableView.vscode.test.ts +++ b/src/test/datascience/variableView/variableView.vscode.test.ts @@ -18,7 +18,7 @@ import { import { waitForVariablesToMatch } from './variableViewHelpers'; import { ITestVariableViewProvider } from './variableViewTestInterfaces'; import { ITestWebviewHost } from '../testInterfaces'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { PythonEnvironment } from '../../../platform/pythonEnvironments/info'; import { IInterpreterService } from '../../../platform/interpreter/contracts'; import { Commands } from '../../../platform/common/constants'; @@ -37,7 +37,7 @@ suite('VariableView @variableViewer', function () { let kernelProvider: IKernelProvider; this.timeout(120_000); suiteSetup(async function () { - traceInfo('Suite Setup'); + logger.info('Suite Setup'); this.timeout(120_000); api = await initialize(); @@ -55,20 +55,20 @@ suite('VariableView @variableViewer', function () { const coreVariableViewProvider = api.serviceContainer.get(IVariableViewProvider); // eslint-disable-next-line @typescript-eslint/no-explicit-any variableViewProvider = coreVariableViewProvider as any as ITestVariableViewProvider; // Cast to expose the test interfaces - traceInfo('Suite Setup (completed)'); + logger.info('Suite Setup (completed)'); }); setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); sinon.restore(); await startJupyterServer(); await createEmptyPythonNotebook(disposables); assert.isOk(window.activeNotebookEditor, 'No active notebook'); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); await closeNotebooksAndCleanUpAfterTests(disposables); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); suiteTeardown(() => closeNotebooksAndCleanUpAfterTests(disposables)); diff --git a/src/test/datascience/widgets/commUtils.ts b/src/test/datascience/widgets/commUtils.ts index 71c701c3cd5..da99a00b70b 100644 --- a/src/test/datascience/widgets/commUtils.ts +++ b/src/test/datascience/widgets/commUtils.ts @@ -3,7 +3,7 @@ import { NotebookCell, NotebookEditor, NotebookRendererMessaging, notebooks } from 'vscode'; import { dispose } from '../../../platform/common/utils/lifecycle'; -import { traceInfo, traceInfoIfCI } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IDisposable } from '../../../platform/common/types'; import { createDeferred } from '../../../platform/common/utils/async'; import { noop } from '../../core'; @@ -18,12 +18,12 @@ export function initializeWidgetComms(disposables: IDisposable[]): Utils { // eslint-disable-next-line @typescript-eslint/no-use-before-define const utils = new Utils(messageChannel, deferred.promise); disposables.push(utils); - traceInfoIfCI(`Adding comm message handler`); + logger.ci(`Adding comm message handler`); const disposable = messageChannel.onDidReceiveMessage(async ({ editor, message }) => { if (message && message.command === 'log') { const messageToLog = message.category === 'error' ? colors.red(message.message) : message.message; const category = message.category ? ` (${message.category})` : ''; - traceInfo(`${colors.yellow('Widget renderer')}${category}: ${messageToLog}`); + logger.info(`${colors.yellow('Widget renderer')}${category}: ${messageToLog}`); } if (message && message.command === 'INIT') { deferred.resolve(editor); @@ -57,7 +57,7 @@ export class Utils { selector }; const editor = await this.editorPromise; - traceInfo(`Sending message to Widget renderer ${JSON.stringify(request)}`); + logger.info(`Sending message to Widget renderer ${JSON.stringify(request)}`); this.messageChannel.postMessage!(request, editor).then(noop, noop); return new Promise((resolve, reject) => { const disposable = this.messageChannel.onDidReceiveMessage(({ message }) => { @@ -81,11 +81,11 @@ export class Utils { selector }; const editor = await this.editorPromise; - traceInfo(`Sending message to Widget renderer ${JSON.stringify(request)}`); + logger.info(`Sending message to Widget renderer ${JSON.stringify(request)}`); this.messageChannel.postMessage!(request, editor).then(noop, noop); return new Promise((resolve, reject) => { const disposable = this.messageChannel.onDidReceiveMessage(({ message }) => { - traceInfo(`Received message (click) from Widget renderer ${JSON.stringify(message)}`); + logger.info(`Received message (click) from Widget renderer ${JSON.stringify(message)}`); if (message && message.requestId === request.requestId) { disposable.dispose(); if (message.error) { @@ -107,11 +107,11 @@ export class Utils { value }; const editor = await this.editorPromise; - traceInfo(`Sending message to Widget renderer ${JSON.stringify(request)}`); + logger.info(`Sending message to Widget renderer ${JSON.stringify(request)}`); this.messageChannel.postMessage!(request, editor).then(noop, noop); return new Promise((resolve, reject) => { const disposable = this.messageChannel.onDidReceiveMessage(({ message }) => { - traceInfo(`Received message (setValue) from Widget renderer ${JSON.stringify(message)}`); + logger.info(`Received message (setValue) from Widget renderer ${JSON.stringify(message)}`); if (message && message.requestId === request.requestId) { disposable.dispose(); if (message.error) { diff --git a/src/test/datascience/widgets/standardWidgets.vscode.common.test.ts b/src/test/datascience/widgets/standardWidgets.vscode.common.test.ts index a0a7e0dd0fc..346f5f0686d 100644 --- a/src/test/datascience/widgets/standardWidgets.vscode.common.test.ts +++ b/src/test/datascience/widgets/standardWidgets.vscode.common.test.ts @@ -18,7 +18,7 @@ import { workspace, WorkspaceEdit } from 'vscode'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IDisposable } from '../../../platform/common/types'; import { captureScreenShot, startJupyterServer, waitForCondition } from '../../common'; import { initialize } from '../../initialize'; @@ -111,17 +111,17 @@ suite('Standard IPyWidget Tests @widgets', function () { let editor: NotebookEditor; let comms: Utils; suiteSetup(async function () { - traceInfo('Suite Setup Standard IPyWidget Tests'); + logger.info('Suite Setup Standard IPyWidget Tests'); this.timeout(120_000); await initialize(); - traceInfo('Suite Setup Standard IPyWidget Tests, Step 2'); + logger.info('Suite Setup Standard IPyWidget Tests, Step 2'); const config = workspace.getConfiguration('jupyter', undefined); await config.update('widgetScriptSources', widgetScriptSourcesValue, ConfigurationTarget.Global); - traceInfo('Suite Setup Standard IPyWidget Tests, Step 3'); + logger.info('Suite Setup Standard IPyWidget Tests, Step 3'); await startJupyterServer(); - traceInfo('Suite Setup Standard IPyWidget Tests, Step 4'); + logger.info('Suite Setup Standard IPyWidget Tests, Step 4'); await prewarmNotebooks(); - traceInfo('Suite Setup Standard IPyWidget Tests, Step 5'); + logger.info('Suite Setup Standard IPyWidget Tests, Step 5'); sinon.restore(); editor = (await createEmptyPythonNotebook(disposables, undefined, true)).editor; await selectDefaultController(editor); @@ -133,24 +133,24 @@ suite('Standard IPyWidget Tests @widgets', function () { await commands.executeCommand('notebook.cell.collapseAllCellInputs'); comms = await initializeWidgetComms(disposables); - traceInfo('Suite Setup (completed)'); + logger.info('Suite Setup (completed)'); }); // Use same notebook without starting kernel in every single test (use one for whole suite). setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); sinon.restore(); await startJupyterServer(); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); // With less realestate, the outputs might not get rendered (VS Code optimization to avoid rendering if not in viewport). await commands.executeCommand('workbench.action.closePanel'); }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); if (this.currentTest?.isFailed()) { await captureScreenShot(this); } // await closeNotebooksAndCleanUpAfterTests(disposables); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); suiteTeardown(async () => closeNotebooksAndCleanUpAfterTests(disposables)); test('Slider Widget', async function () { diff --git a/src/test/datascience/widgets/thirdpartyWidgets.vscode.common.test.ts b/src/test/datascience/widgets/thirdpartyWidgets.vscode.common.test.ts index 62c92c9cdd8..1fb7fd4632d 100644 --- a/src/test/datascience/widgets/thirdpartyWidgets.vscode.common.test.ts +++ b/src/test/datascience/widgets/thirdpartyWidgets.vscode.common.test.ts @@ -4,7 +4,7 @@ /* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires */ import * as sinon from 'sinon'; import { commands, ConfigurationTarget, Memento, NotebookEditor, window, workspace } from 'vscode'; -import { traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { GLOBAL_MEMENTO, IConfigurationService, @@ -51,7 +51,7 @@ import { isWeb } from '../../../platform/common/utils/misc'; if (isWeb()) { return this.skip(); } - traceInfo('Suite Setup VS Code Notebook - Execution'); + logger.info('Suite Setup VS Code Notebook - Execution'); this.timeout(120_000); api = await initialize(); const config = workspace.getConfiguration('jupyter', undefined); @@ -75,22 +75,22 @@ import { isWeb } from '../../../platform/common/utils/misc'; await commands.executeCommand('workbench.action.maximizeEditorHideSidebar'); comms = await initializeWidgetComms(disposables); - traceInfo('Suite Setup (completed)'); + logger.info('Suite Setup (completed)'); }); // Use same notebook without starting kernel in every single test (use one for whole suite). setup(async function () { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); sinon.restore(); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); // With less real estate, the outputs might not get rendered (VS Code optimization to avoid rendering if not in viewport). await commands.executeCommand('workbench.action.closePanel'); }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); if (this.currentTest?.isFailed()) { await captureScreenShot(this); } - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); suiteTeardown(async () => closeNotebooksAndCleanUpAfterTests(disposables)); test('Slider Widget', async function () { diff --git a/src/test/extension.serviceRegistry.vscode.test.ts b/src/test/extension.serviceRegistry.vscode.test.ts index dc5de22fd7b..e1ec01400d4 100644 --- a/src/test/extension.serviceRegistry.vscode.test.ts +++ b/src/test/extension.serviceRegistry.vscode.test.ts @@ -3,7 +3,7 @@ /* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires */ import { assert } from 'chai'; -import { traceInfo } from '../platform/logging'; +import { logger } from '../platform/logging'; import { captureScreenShot, IExtensionTestApi, testMandatory } from './common.node'; import * as ts from 'typescript'; @@ -132,17 +132,17 @@ suite('Verify serviceRegistry is correct', function () { let api: IExtensionTestApi; setup(async function () { try { - traceInfo(`Start Test ${this.currentTest?.title}`); + logger.info(`Start Test ${this.currentTest?.title}`); api = await initialize(); - traceInfo(`Start Test (completed) ${this.currentTest?.title}`); + logger.info(`Start Test (completed) ${this.currentTest?.title}`); } catch (e) { await captureScreenShot(this); throw e; } }); teardown(async function () { - traceInfo(`Ended Test ${this.currentTest?.title}`); - traceInfo(`Ended Test (completed) ${this.currentTest?.title}`); + logger.info(`Ended Test ${this.currentTest?.title}`); + logger.info(`Ended Test (completed) ${this.currentTest?.title}`); }); testMandatory('Verify all classes with inject on them are in the container', async () => { assert.ok( diff --git a/src/test/interpreters/condaService.node.ts b/src/test/interpreters/condaService.node.ts index 2dbe6917f67..0be359a2310 100644 --- a/src/test/interpreters/condaService.node.ts +++ b/src/test/interpreters/condaService.node.ts @@ -5,7 +5,7 @@ import glob from 'glob'; import * as path from '../../platform/vscode-path/path'; import { parse, SemVer } from 'semver'; import { promisify } from 'util'; -import { traceError, traceVerbose, traceWarning } from '../../platform/logging'; +import { logger } from '../../platform/logging'; import { arePathsSame } from '../../platform/common/platform/fileUtils.node'; import { ProcessService } from '../../platform/common/process/proc.node'; import { parseCondaEnvFileContents } from './condaHelper'; @@ -66,7 +66,7 @@ const CondaLocationsGlobWin = `{${condaGlobPathsForWindows.join(',')}}`; async function getCondaFileFromKnownLocations(): Promise { const globPattern = getOSType() === OSType.Windows ? CondaLocationsGlobWin : CondaLocationsGlob; const condaFiles = await promisify(glob)(globPattern).catch((failReason) => { - traceWarning( + logger.warn( 'Default conda location search failed.', `Searching for default install locations for conda results in error: ${failReason}` ); @@ -134,7 +134,7 @@ async function getCondaVersion(): Promise { return version; } // Use a bogus version, at least to indicate the fact that a version was returned. - traceWarning(`Unable to parse Version of Conda, ${versionString}`); + logger.warn(`Unable to parse Version of Conda, ${versionString}`); return new SemVer('0.0.1'); } @@ -148,9 +148,9 @@ async function getCondaEnvironments(): Promise output.stdout); - traceVerbose(`Conda Env List ${envInfo}}`); + logger.debug(`Conda Env List ${envInfo}}`); if (!envInfo) { - traceVerbose('Conda env list failure, attempting path additions.'); + logger.debug('Conda env list failure, attempting path additions.'); // Try adding different folders to the path. Miniconda fails to run // without them. const baseFolder = path.dirname(path.dirname(condaFile)); @@ -159,7 +159,7 @@ async function getCondaEnvironments(): Promise output.stdout); @@ -171,7 +171,7 @@ async function getCondaEnvironments(): Promise { @@ -89,7 +89,7 @@ suite('Smoke Tests', function () { if (await fs.pathExists(outputFile)) { await fs.unlink(outputFile); } - traceInfo(`Opening notebook file ${file}`); + logger.info(`Opening notebook file ${file}`); const notebook = await vscode.workspace.openNotebookDocument(vscode.Uri.file(file)); await vscode.window.showNotebookDocument(notebook); diff --git a/src/test/testHooks.node.ts b/src/test/testHooks.node.ts index fe63e1104ad..cc27eabc477 100644 --- a/src/test/testHooks.node.ts +++ b/src/test/testHooks.node.ts @@ -6,13 +6,13 @@ import { AppinsightsKey, Telemetry } from '../platform/common/constants'; import TelemetryReporter from '@vscode/extension-telemetry'; import { IS_CI_SERVER } from './ciConstants.node'; import { sleep } from '../platform/common/utils/async'; -import { traceInfoIfCI } from '../platform/logging'; +import { logger } from '../platform/logging'; let telemetryReporter: TelemetryReporter; export const rootHooks: Mocha.RootHookObject = { beforeAll() { - traceInfoIfCI(`Environment Variable dump: ${JSON.stringify(process.env)}`); + logger.ci(`Environment Variable dump: ${JSON.stringify(process.env)}`); if (!IS_CI_SERVER) { return; } @@ -22,7 +22,7 @@ export const rootHooks: Mocha.RootHookObject = { telemetryReporter = new reporter(AppinsightsKey); }, afterEach(this: Context) { - traceInfoIfCI('Root afterEach'); + logger.ci('Root afterEach'); if ( !IS_CI_SERVER || !process.env.GITHUB_REF_NAME || @@ -45,7 +45,7 @@ export const rootHooks: Mocha.RootHookObject = { dimensions = { ...dimensions, commitHash: process.env.GITHUB_SHA }; } - traceInfoIfCI(`Sending telemetry event ${Telemetry.RunTest} with dimensions ${JSON.stringify(dimensions)}`); + logger.ci(`Sending telemetry event ${Telemetry.RunTest} with dimensions ${JSON.stringify(dimensions)}`); telemetryReporter.sendDangerousTelemetryEvent(Telemetry.RunTest, dimensions, measures); }, afterAll: async () => { diff --git a/src/test/web/customReporter.ts b/src/test/web/customReporter.ts index 57f2db1f8d8..7d93a5b48ee 100644 --- a/src/test/web/customReporter.ts +++ b/src/test/web/customReporter.ts @@ -183,12 +183,15 @@ class ConsoleHijacker implements ILogger { traceEverything(message: string, ...data: Arguments): void { this.logMessage(undefined, message, data); } - verbose(message: string, ...data: Arguments): void { + debug(message: string, ...data: Arguments): void { this.logMessage(undefined, message, data); } trace(message: string, ...data: Arguments): void { this.logMessage(undefined, message, data); } + ci(_message: any, ..._data: Arguments): void { + // + } logMessage(category: 'error' | 'warn' | undefined, message: string, ...data: Arguments) { if (!this.captureLogs) { return; diff --git a/src/webviews/extension-side/dataviewer/baseDataViewerDependencyImplementation.ts b/src/webviews/extension-side/dataviewer/baseDataViewerDependencyImplementation.ts index c0722558a39..536dbd001e2 100644 --- a/src/webviews/extension-side/dataviewer/baseDataViewerDependencyImplementation.ts +++ b/src/webviews/extension-side/dataviewer/baseDataViewerDependencyImplementation.ts @@ -12,7 +12,7 @@ import { capturePerfTelemetry, sendTelemetryEvent, Telemetry } from '../../../te import { ProductNames } from '../../../platform/interpreter/installer/productNames'; import { Product } from '../../../platform/interpreter/installer/types'; import { CancellationToken, CancellationTokenSource, window } from 'vscode'; -import { traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { isCodeSpace } from '../../../platform/constants'; /** @@ -29,7 +29,7 @@ export abstract class BaseDataViewerDependencyImplementation implemen const version = await this._getVersion(executer, token); return typeof version === 'string' ? parseSemVer(version) : version; } catch (e) { - traceWarning(DataScience.failedToGetVersionOfPandas, e.message); + logger.warn(DataScience.failedToGetVersionOfPandas, e.message); return; } } diff --git a/src/webviews/extension-side/dataviewer/dataViewer.ts b/src/webviews/extension-side/dataviewer/dataViewer.ts index 36cf063cf7b..e90bdb3fd66 100644 --- a/src/webviews/extension-side/dataviewer/dataViewer.ts +++ b/src/webviews/extension-side/dataviewer/dataViewer.ts @@ -22,7 +22,7 @@ import { CheckboxState } from '../../../platform/telemetry/constants'; import { IKernel } from '../../../kernels/types'; import { IWebviewPanelProvider } from '../../../platform/common/application/types'; import { HelpLinks, Telemetry } from '../../../platform/common/constants'; -import { traceError, traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { IConfigurationService, IMemento, @@ -98,7 +98,7 @@ export class DataViewer extends WebviewPanelHost implements this.dataProvider = dataProvider; // Load the web panel using our current directory as we don't expect to load any other files - await super.loadWebview(Uri.file(process.cwd())).catch(traceError); + await super.loadWebview(Uri.file(process.cwd())).catch(logger.error); super.setTitle(title); @@ -149,7 +149,7 @@ export class DataViewer extends WebviewPanelHost implements dataFrameInfo = await this.getDataFrameInfo(newSlice); } } - traceInfo(`Refreshing data viewer for variable ${dataFrameInfo.name}`); + logger.info(`Refreshing data viewer for variable ${dataFrameInfo.name}`); // Send a message with our data this.postMessage(DataViewerMessages.InitializeData, dataFrameInfo).catch(noop); } @@ -287,7 +287,7 @@ export class DataViewer extends WebviewPanelHost implements return await func(); } catch (e) { if (e instanceof JupyterDataRateLimitError) { - traceError(e.message); + logger.error(e.message); const actionTitle = localize.DataScience.pythonInteractiveHelpLink; window.showErrorMessage(localize.DataScience.jupyterDataRateExceeded, actionTitle).then((v) => { // User clicked on the link, open it. @@ -297,7 +297,7 @@ export class DataViewer extends WebviewPanelHost implements }, noop); this.dispose(); } - traceError(e); + logger.error(e); this.errorHandler.handleError(e).then(noop, noop); } finally { this.sendElapsedTimeTelemetry(); diff --git a/src/webviews/extension-side/dataviewer/dataViewerCommandRegistry.ts b/src/webviews/extension-side/dataviewer/dataViewerCommandRegistry.ts index d87f6c7383d..27505607138 100644 --- a/src/webviews/extension-side/dataviewer/dataViewerCommandRegistry.ts +++ b/src/webviews/extension-side/dataviewer/dataViewerCommandRegistry.ts @@ -23,7 +23,7 @@ import { DataScience } from '../../../platform/common/utils/localize'; import { noop } from '../../../platform/common/utils/misc'; import { untildify } from '../../../platform/common/utils/platform'; import { IInterpreterService } from '../../../platform/interpreter/contracts'; -import { traceError, traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { sendTelemetryEvent } from '../../../telemetry'; import { EventName } from '../../../platform/telemetry/constants'; import { IDataScienceErrorHandler } from '../../../kernels/errors/types'; @@ -145,7 +145,7 @@ export class DataViewerCommandRegistry implements IExtensionSyncActivationServic } } catch (e) { sendTelemetryEvent(EventName.OPEN_DATAVIEWER_FROM_VARIABLE_WINDOW_ERROR, undefined, undefined, e); - traceError(e); + logger.error(e); this.errorHandler.handleError(e).then(noop, noop); } } else { @@ -163,7 +163,7 @@ export class DataViewerCommandRegistry implements IExtensionSyncActivationServic return await this.dataViewerFactory.create(jupyterVariableDataProvider, title); } } catch (e) { - traceError(e); + logger.error(e); sendTelemetryEvent(Telemetry.FailedShowDataViewer); window.showErrorMessage(DataScience.showDataViewerFail).then(noop, noop); } @@ -210,17 +210,17 @@ export class DataViewerCommandRegistry implements IExtensionSyncActivationServic ): Promise { if (!this.interpreterService) { // Interpreter service is optional - traceInfo('Interpreter Service missing when trying getDebugAdapterPython'); + logger.info('Interpreter Service missing when trying getDebugAdapterPython'); return; } // Check debugAdapterPython and pythonPath let pythonPath: string = ''; if (debugConfiguration.debugAdapterPython !== undefined) { - traceInfo('Found debugAdapterPython on Debug Configuration to use'); + logger.info('Found debugAdapterPython on Debug Configuration to use'); pythonPath = debugConfiguration.debugAdapterPython; } else if (debugConfiguration.pythonPath) { - traceInfo('Found pythonPath on Debug Configuration to use'); + logger.info('Found pythonPath on Debug Configuration to use'); pythonPath = debugConfiguration.pythonPath; } diff --git a/src/webviews/extension-side/dataviewer/interpreterDataViewerDependencyImplementation.node.ts b/src/webviews/extension-side/dataviewer/interpreterDataViewerDependencyImplementation.node.ts index cc2a5aebee0..78d531c5cb1 100644 --- a/src/webviews/extension-side/dataviewer/interpreterDataViewerDependencyImplementation.node.ts +++ b/src/webviews/extension-side/dataviewer/interpreterDataViewerDependencyImplementation.node.ts @@ -9,7 +9,7 @@ import { IPythonExecutionFactory } from '../../../platform/interpreter/types.nod import { PythonEnvironment } from '../../../platform/pythonEnvironments/info'; import { sendTelemetryEvent, Telemetry } from '../../../telemetry'; import { BaseDataViewerDependencyImplementation } from './baseDataViewerDependencyImplementation'; -import { traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { DataScience } from '../../../platform/common/utils/localize'; import { splitLines } from '../../../platform/common/helpers'; @@ -42,7 +42,7 @@ export class InterpreterDataViewerDependencyImplementation extends BaseDataViewe const output = result.stdout; if (!output?.includes(separator)) { - traceWarning(DataScience.failedToGetVersionOfPandas, `Output is ${output}`); + logger.warn(DataScience.failedToGetVersionOfPandas, `Output is ${output}`); return ''; } const items = splitLines(output.trim()); diff --git a/src/webviews/extension-side/dataviewer/jupyterVariableDataProvider.ts b/src/webviews/extension-side/dataviewer/jupyterVariableDataProvider.ts index 4974359aaf7..bae9d15a806 100644 --- a/src/webviews/extension-side/dataviewer/jupyterVariableDataProvider.ts +++ b/src/webviews/extension-side/dataviewer/jupyterVariableDataProvider.ts @@ -12,7 +12,7 @@ import { } from './types'; import { IKernel } from '../../../kernels/types'; import { IJupyterVariable, IJupyterVariables } from '../../../kernels/variables/types'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { Identifiers } from '../../../platform/common/constants'; import { getFilePath } from '../../../platform/common/platform/fs-paths'; import { isWeb } from '../../../platform/common/utils/misc'; @@ -76,7 +76,7 @@ export class JupyterVariableDataProvider implements IJupyterVariableDataProvider .map((shapeEl) => parseInt(shapeEl)); } } catch (e) { - traceError(`Could not parse IJupyterVariable with malformed shape: ${shape}`); + logger.error(`Could not parse IJupyterVariable with malformed shape: ${shape}`); } return undefined; } diff --git a/src/webviews/extension-side/dataviewer/kernelDataViewerDependencyImplementation.ts b/src/webviews/extension-side/dataviewer/kernelDataViewerDependencyImplementation.ts index b27ebbe4905..443d16c366c 100644 --- a/src/webviews/extension-side/dataviewer/kernelDataViewerDependencyImplementation.ts +++ b/src/webviews/extension-side/dataviewer/kernelDataViewerDependencyImplementation.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { traceWarning } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { DataScience } from '../../../platform/common/utils/localize'; import { EnvironmentType } from '../../../platform/pythonEnvironments/info'; import { sendTelemetryEvent, Telemetry } from '../../../telemetry'; @@ -34,7 +34,7 @@ export class KernelDataViewerDependencyImplementation extends BaseDataViewerDepe const outputs = await executeSilently(kernel.session.kernel, command); const error = outputs.find((item) => item.output_type === 'error'); if (error) { - traceWarning(DataScience.failedToGetVersionOfPandas, error.message); + logger.warn(DataScience.failedToGetVersionOfPandas, error.message); } return outputs.map((item) => item.text?.toString()); } @@ -43,7 +43,7 @@ export class KernelDataViewerDependencyImplementation extends BaseDataViewerDepe const outputs = await this.execute(kernelGetPandasVersion, kernel); const output = outputs.map((text) => (text ? text.toString() : undefined)).find((item) => item); if (!output?.includes(separator)) { - traceWarning(DataScience.failedToGetVersionOfPandas, `Output is ${output}`); + logger.warn(DataScience.failedToGetVersionOfPandas, `Output is ${output}`); return ''; } const items = splitLines(output.trim()); diff --git a/src/webviews/extension-side/ipywidgets/rendererComms.ts b/src/webviews/extension-side/ipywidgets/rendererComms.ts index e550c9b3259..3aad55c9a24 100644 --- a/src/webviews/extension-side/ipywidgets/rendererComms.ts +++ b/src/webviews/extension-side/ipywidgets/rendererComms.ts @@ -13,7 +13,7 @@ import { WIDGET_MIMETYPE } from '../../../platform/common/constants'; import { dispose } from '../../../platform/common/utils/lifecycle'; import { IDisposable } from '../../../platform/common/types'; import { noop } from '../../../platform/common/utils/misc'; -import { traceTrace } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; type WidgetData = { model_id: string; @@ -140,13 +140,13 @@ export class IPyWidgetRendererComms implements IExtensionSyncActivationService { // } const version = kernel?.ipywidgetsVersion; // || versionInWidgetState; if (kernel?.ipywidgetsVersion) { - traceTrace(`IPyWidget version in Kernel is ${kernel?.ipywidgetsVersion}.`); + logger.trace(`IPyWidget version in Kernel is ${kernel?.ipywidgetsVersion}.`); } // if (versionInWidgetState) { - // traceTrace(`IPyWidget version in Kernel is ${versionInWidgetState}.`); + // logger.trace(`IPyWidget version in Kernel is ${versionInWidgetState}.`); // } // if (kernel?.ipywidgetsVersion && versionInWidgetState) { - // traceWarning( + // logger.warn( // `IPyWidget version in Kernel is ${kernel?.ipywidgetsVersion} and in widget state is ${versionInWidgetState}.}` // ); // } diff --git a/src/webviews/extension-side/plotView/plotSaveHandler.ts b/src/webviews/extension-side/plotView/plotSaveHandler.ts index 603778b1bef..9033fe1111b 100644 --- a/src/webviews/extension-side/plotView/plotSaveHandler.ts +++ b/src/webviews/extension-side/plotView/plotSaveHandler.ts @@ -4,7 +4,7 @@ import { inject, injectable } from 'inversify'; import { NotebookCellOutput, NotebookDocument, Uri, window, workspace } from 'vscode'; import * as path from '../../../platform/vscode-path/path'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { getDisplayPath } from '../../../platform/common/platform/fs-paths'; import { IFileSystem } from '../../../platform/common/platform/types'; import { DataScience } from '../../../platform/common/utils/localize'; @@ -28,10 +28,12 @@ export class PlotSaveHandler implements IPlotSaveHandler { } const output = getOutputItem(notebook, outputId, mimeType); if (!output) { - return traceError(`No plot to save ${getDisplayPath(notebook.uri)}, id: ${outputId} for ${mimeType}`); + return logger.error(`No plot to save ${getDisplayPath(notebook.uri)}, id: ${outputId} for ${mimeType}`); } if (!(mimeType.toLowerCase() in imageExtensionForMimeType)) { - return traceError(`Unsupported MimeType ${getDisplayPath(notebook.uri)}, id: ${outputId} for ${mimeType}`); + return logger.error( + `Unsupported MimeType ${getDisplayPath(notebook.uri)}, id: ${outputId} for ${mimeType}` + ); } const saveLocation = await this.getSaveTarget(output, mimeType); @@ -87,7 +89,7 @@ export class PlotSaveHandler implements IPlotSaveHandler { } protected async saveAsPdf(_output: NotebookCellOutput, _target: Uri) { - return traceError(`Save as PDF is not yet supported on the web.`); + return logger.error(`Save as PDF is not yet supported on the web.`); } } diff --git a/src/webviews/extension-side/plotView/plotViewHandler.ts b/src/webviews/extension-side/plotView/plotViewHandler.ts index e1d8914121a..3c920486d16 100644 --- a/src/webviews/extension-side/plotView/plotViewHandler.ts +++ b/src/webviews/extension-side/plotView/plotViewHandler.ts @@ -3,7 +3,7 @@ import { inject, injectable } from 'inversify'; import { NotebookCellOutputItem, NotebookDocument } from 'vscode'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { getDisplayPath } from '../../../platform/common/platform/fs-paths'; import { IPlotViewerProvider } from '../plotting/types'; import { uint8ArrayToBase64 } from '../../../platform/common/utils/string'; @@ -26,7 +26,7 @@ export class PlotViewHandler { const pngOutput = getOutputItem(notebook, outputId, pngMimeType); if (!pngOutput) { - return traceError(`No SVG or PNG Plot to open ${getDisplayPath(notebook.uri)}, id: ${outputId}`); + return logger.error(`No SVG or PNG Plot to open ${getDisplayPath(notebook.uri)}, id: ${outputId}`); } // If we did find a PNG wrap it in an SVG element so that we can display it diff --git a/src/webviews/extension-side/plotting/plotViewer.node.ts b/src/webviews/extension-side/plotting/plotViewer.node.ts index 102994afbb7..f21c6fdff8f 100644 --- a/src/webviews/extension-side/plotting/plotViewer.node.ts +++ b/src/webviews/extension-side/plotting/plotViewer.node.ts @@ -4,7 +4,7 @@ import { inject, injectable } from 'inversify'; import * as path from '../../../platform/vscode-path/path'; import { Uri, window } from 'vscode'; -import { traceError, traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { createDeferred } from '../../../platform/common/utils/async'; import { IExportPlotRequest } from './types'; import { IFileSystemNode } from '../../../platform/common/platform/types.node'; @@ -27,7 +27,7 @@ export class PlotViewer extends PlotViewerBase { } protected override async exportPlot(payload: IExportPlotRequest): Promise { - traceInfo('exporting plot...'); + logger.info('exporting plot...'); const filtersObject: Record = {}; filtersObject[localize.DataScience.pdfFilter] = ['pdf']; filtersObject[localize.DataScience.pngFilter] = ['png']; @@ -59,14 +59,14 @@ export class PlotViewer extends PlotViewerBase { } } } catch (e) { - traceError(e); + logger.error(e); window.showErrorMessage(localize.DataScience.exportImageFailed(e)).then(noop, noop); } } } export async function saveSvgToPdf(svg: string, fs: IFileSystemNode, file: Uri) { - traceInfo('Attempting pdf write...'); + logger.info('Attempting pdf write...'); // Import here since pdfkit is so huge. const SVGtoPDF = (await import('svg-to-pdfkit')).default; const deferred = createDeferred(); @@ -74,14 +74,14 @@ export async function saveSvgToPdf(svg: string, fs: IFileSystemNode, file: Uri) const pdfkit = require('pdfkit/js/pdfkit.standalone') as typeof import('pdfkit'); const doc = new pdfkit(); const ws = fs.createLocalWriteStream(file.fsPath); - traceInfo(`Writing pdf to ${file.fsPath}`); + logger.info(`Writing pdf to ${file.fsPath}`); ws.on('finish', () => deferred.resolve); // See docs or demo from source https://cdn.statically.io/gh/alafr/SVG-to-PDFKit/master/examples/demo.htm // How to resize to fit (fit within the height & width of page). SVGtoPDF(doc, svg, 0, 0, { preserveAspectRatio: 'xMinYMin meet' }); doc.pipe(ws); doc.end(); - traceInfo(`Finishing pdf to ${file.fsPath}`); + logger.info(`Finishing pdf to ${file.fsPath}`); await deferred.promise; - traceInfo(`Completed pdf to ${file.fsPath}`); + logger.info(`Completed pdf to ${file.fsPath}`); } diff --git a/src/webviews/extension-side/plotting/plotViewer.ts b/src/webviews/extension-side/plotting/plotViewer.ts index 38a67ac6eeb..1e7972b0b02 100644 --- a/src/webviews/extension-side/plotting/plotViewer.ts +++ b/src/webviews/extension-side/plotting/plotViewer.ts @@ -5,7 +5,7 @@ import { inject, injectable } from 'inversify'; import * as path from '../../../platform/vscode-path/path'; import { Event, EventEmitter, Uri, ViewColumn, window } from 'vscode'; -import { traceError, traceInfo } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { PlotViewerMessageListener } from './plotViewerMessageListener'; import { IExportPlotRequest, IPlotViewer, IPlotViewerMapping, PlotViewerMessages } from './types'; import { IWebviewPanelProvider } from '../../../platform/common/application/types'; @@ -44,7 +44,7 @@ export class PlotViewer extends WebviewPanelHost implements // Load the web panel using our current directory as we don't expect to load any other files super .loadWebview(Uri.file(process.cwd())) - .catch(traceError) + .catch(logger.error) .finally(() => { // Send our telemetry for the webview loading when the load is done. sendTelemetryEvent(Telemetry.PlotViewerWebviewLoaded, { duration: startupTimer.elapsedTime }); @@ -121,7 +121,7 @@ export class PlotViewer extends WebviewPanelHost implements } protected async exportPlot(payload: IExportPlotRequest): Promise { - traceInfo('exporting plot...'); + logger.info('exporting plot...'); const filtersObject: Record = {}; filtersObject[localize.DataScience.pngFilter] = ['png']; filtersObject[localize.DataScience.svgFilter] = ['svg']; @@ -148,7 +148,7 @@ export class PlotViewer extends WebviewPanelHost implements } } } catch (e) { - traceError(e); + logger.error(e); window.showErrorMessage(localize.DataScience.exportImageFailed(e.toString())).then(noop, noop); } } diff --git a/src/webviews/extension-side/variablesView/variableView.ts b/src/webviews/extension-side/variablesView/variableView.ts index b84ec10fa8c..f86a41ffd69 100644 --- a/src/webviews/extension-side/variablesView/variableView.ts +++ b/src/webviews/extension-side/variablesView/variableView.ts @@ -15,7 +15,7 @@ import { } from '../../../kernels/variables/types'; import { IWebviewViewProvider } from '../../../platform/common/application/types'; import { ContextKey } from '../../../platform/common/contextKey'; -import { traceError } from '../../../platform/logging'; +import { logger } from '../../../platform/logging'; import { Resource, IConfigurationService, @@ -63,7 +63,7 @@ export class VariableView extends WebviewViewHost imp @capturePerfTelemetry(Telemetry.NativeVariableViewLoaded) public async load(codeWebview: vscodeWebviewView) { - await super.loadWebview(Uri.file(process.cwd()), codeWebview).catch(traceError); + await super.loadWebview(Uri.file(process.cwd()), codeWebview).catch(logger.error); // After loading, hook up our visibility watch and check the initial visibility if (this.webviewView) { @@ -183,7 +183,7 @@ export class VariableView extends WebviewViewHost imp return commands.executeCommand(Commands.ShowDataViewer, request.variable); } } catch (e) { - traceError(e); + logger.error(e); sendTelemetryEvent(Telemetry.FailedShowDataViewer); window.showErrorMessage(localize.DataScience.showDataViewerFail).then(noop, noop); }