From d6ace1d5abdd0941c7b66072e4783b9d0a0554a3 Mon Sep 17 00:00:00 2001 From: Takashi Tamura Date: Sun, 1 Oct 2023 10:51:36 +0900 Subject: [PATCH] Uset util.inspect() instead of JSON.stringify() for logging. --- src/components/builder.ts | 3 ++- src/components/configuration.ts | 3 ++- src/components/eventbus.ts | 3 ++- src/components/locator.ts | 5 +++-- src/components/locatorlib/synctex.ts | 9 +++++---- src/components/logger.ts | 3 ++- src/components/manager.ts | 3 ++- src/components/managerlib/bibwatcher.ts | 3 ++- src/components/managerlib/managerwatcher.ts | 3 ++- src/components/managerlib/pdfwatcher.ts | 5 +++-- src/components/server.ts | 13 +++++++------ src/components/viewer.ts | 19 ++++++++++--------- src/components/viewerlib/pdfviewerpanel.ts | 3 ++- src/providers/completionlib/command.ts | 3 ++- src/providers/completionlib/environment.ts | 3 ++- src/providersmanager.ts | 3 ++- src/utils/inspect.ts | 9 +++++++++ 17 files changed, 59 insertions(+), 34 deletions(-) create mode 100644 src/utils/inspect.ts diff --git a/src/components/builder.ts b/src/components/builder.ts index e022240e..037c6079 100644 --- a/src/components/builder.ts +++ b/src/components/builder.ts @@ -12,6 +12,7 @@ import type { Manager } from './manager' import type { LwStatusBarItem } from './statusbaritem' import { statPath } from '../lib/lwfs/lwfs' import { ExternalPromise } from '../utils/externalpromise' +import { inspectCompact } from '../utils/inspect' const maxPrintLine = '10000' @@ -245,7 +246,7 @@ export class Builder { private buildStep(rootFile: string, step: StepCommand, {stepIndex, totalStepsLength}: {stepIndex: number, totalStepsLength: number}) { this.extension.logger.logCommand(`Recipe step ${stepIndex}`, step.command, step.args) - this.extension.logger.info(`Recipe step env: ${JSON.stringify(step.env)}`) + this.extension.logger.info(`Recipe step env: ${inspectCompact(step.env)}`) const envVars = Object.create(null) as ProcessEnv Object.keys(process.env).forEach(key => envVars[key] = process.env[key]) const currentEnv = step.env diff --git a/src/components/configuration.ts b/src/components/configuration.ts index 1c355fb1..da18568e 100644 --- a/src/components/configuration.ts +++ b/src/components/configuration.ts @@ -1,5 +1,6 @@ import * as vscode from 'vscode' import { Logger } from './logger' +import { inspectReadable } from '../utils/inspect' export class Configuration { @@ -35,7 +36,7 @@ export class Configuration { const configuration = vscode.workspace.getConfiguration(undefined, workspace) for(const config of this.configurationsToLog) { const value = configuration.get(config) - this.extension.logger.info(`${config}: ${JSON.stringify(value, null, ' ')}`) + this.extension.logger.info(`${config}: ${inspectReadable(value)}`) } } } diff --git a/src/components/eventbus.ts b/src/components/eventbus.ts index 47845f24..eda40341 100644 --- a/src/components/eventbus.ts +++ b/src/components/eventbus.ts @@ -2,6 +2,7 @@ import type * as vscode from 'vscode' import type {PdfViewerState} from '../../types/latex-toybox-protocol-types/index' import { AwaitableEventEmitter } from './eventbuslib/awaitableeventemitter' import type { Logger } from './logger' +import { inspectCompact } from '../utils/inspect' export type EventName = 'auxupdated' | @@ -41,7 +42,7 @@ export class EventBus { }) { this.allEmitters.forEach((emitter) => { emitter.event((arg) => { - extension.logger.debug(`Event ${emitter.eventName} triggered. Payload: ${JSON.stringify(arg)}`) + extension.logger.debug(`Event ${emitter.eventName} triggered. Payload: ${inspectCompact(arg)}`) }) }) } diff --git a/src/components/locator.ts b/src/components/locator.ts index 0ddec716..c0688680 100644 --- a/src/components/locator.ts +++ b/src/components/locator.ts @@ -12,6 +12,7 @@ import type { Logger } from './logger' import type { Manager } from './manager' import type { Viewer } from './viewer' import { ExternalPromise } from '../utils/externalpromise' +import { inspectCompact } from '../utils/inspect' export type SyncTeXRecordForward = { page: number, @@ -177,7 +178,7 @@ export class Locator { private invokeSyncTeXCommandForward(line: number, col: number, filePath: string, pdfFile: string): Thenable { const configuration = vscode.workspace.getConfiguration('latex-toybox') const args = ['view', '-i', `${line}:${col + 1}:${filePath}`, '-o', pdfFile] - this.extension.logger.info(`Execute synctex with args ${JSON.stringify(args)}`) + this.extension.logger.info(`Execute synctex with args ${inspectCompact(args)}`) const command = configuration.get('synctex.path') as string const proc = cp.spawn(command, args, {cwd: path.dirname(pdfFile)}) @@ -227,7 +228,7 @@ export class Locator { const configuration = vscode.workspace.getConfiguration('latex-toybox') const args = ['edit', '-o', `${page}:${x}:${y}:${pdfPath}`] - this.extension.logger.info(`Executing synctex with args ${JSON.stringify(args)}`) + this.extension.logger.info(`Executing synctex with args: ${inspectCompact(args)}`) const command = configuration.get('synctex.path') as string const proc = cp.spawn(command, args, {cwd: path.dirname(pdfPath)}) diff --git a/src/components/locatorlib/synctex.ts b/src/components/locatorlib/synctex.ts index cade6588..fd72fab4 100644 --- a/src/components/locatorlib/synctex.ts +++ b/src/components/locatorlib/synctex.ts @@ -7,6 +7,7 @@ import {iconvLiteSupportedEncodings} from '../../utils/convertfilename' import {isSameRealPath} from '../../utils/pathnormalize' import { existsPath, readFileAsBuffer } from '../../lib/lwfs/lwfs' import type { ILogger } from '../../interfaces' +import { inspectCompact } from '../../utils/inspect' class Rectangle { @@ -110,7 +111,7 @@ export class SyncTexJs { } if (!await existsPath(synctexFile) && !await existsPath(synctexFileGz)) { - this.extension.logger.error(`[SyncTexJs] .synctex and .synctex.gz file not found: ${JSON.stringify({synctexFile, synctexFileGz})}`) + this.extension.logger.error(`[SyncTexJs] .synctex and .synctex.gz file not found: ${inspectCompact({synctexFile, synctexFileGz})}`) } throw new SyncTexJsError(`parseSyncTexForPdf failed with: ${pdfFile}`) @@ -139,13 +140,13 @@ export class SyncTexJs { } async syncTexJsForward(line: number, filePath: string, pdfFile: string) { - this.extension.logger.info(`[SyncTexJs] Execute syncTexJsForward: ${JSON.stringify({pdfFile, filePath, line})}`) + this.extension.logger.info(`[SyncTexJs] Execute syncTexJsForward: ${inspectCompact({pdfFile, filePath, line})}`) const pdfSyncObject = await this.parseSyncTexForPdf(pdfFile) const inputFilePath = await this.findInputFilePathForward(filePath, pdfSyncObject) if (inputFilePath === undefined) { const inputFiles = Object.keys(pdfSyncObject.blockNumberLine) const inputFilesStr = JSON.stringify(inputFiles, null, ' ') - throw new SyncTexJsError(`[SyncTexJs] No relevant entry of the tex file found in the synctex file: ${JSON.stringify({filePath, pdfFile, line, inputFilesStr})}`) + throw new SyncTexJsError(`[SyncTexJs] No relevant entry of the tex file found in the synctex file: ${inspectCompact({filePath, pdfFile, line, inputFilesStr})}`) } const linePageBlocks = pdfSyncObject.blockNumberLine[inputFilePath] @@ -183,7 +184,7 @@ export class SyncTexJs { } async syncTexJsBackward(page: number, x: number, y: number, pdfPath: string) { - this.extension.logger.info(`[SyncTexJs] Execute syncTexJsBackward: ${JSON.stringify({pdfPath, page, x, y})}`) + this.extension.logger.info(`[SyncTexJs] Execute syncTexJsBackward: ${inspectCompact({pdfPath, page, x, y})}`) const pdfSyncObject = await this.parseSyncTexForPdf(pdfPath) const y0 = y - pdfSyncObject.offset.y const x0 = x - pdfSyncObject.offset.x diff --git a/src/components/logger.ts b/src/components/logger.ts index 1ad48397..5e2bcc22 100644 --- a/src/components/logger.ts +++ b/src/components/logger.ts @@ -1,5 +1,6 @@ import * as vscode from 'vscode' import { ILogger } from '../interfaces' +import { inspectCompact } from '../utils/inspect' export class Logger implements ILogger { @@ -16,7 +17,7 @@ export class Logger implements ILogger { logCommand(message: string, command: string, args: readonly string[] = []) { this.info(message + ': ' + command) - this.info(message + ' args: ' + JSON.stringify(args)) + this.info(message + ' args: ' + inspectCompact(args)) } debug(message: string) { diff --git a/src/components/manager.ts b/src/components/manager.ts index 24a8da2d..27eda950 100644 --- a/src/components/manager.ts +++ b/src/components/manager.ts @@ -31,6 +31,7 @@ import type { Commander } from '../commander' import type { DuplicateLabels } from './duplicatelabels' import type { CompletionUpdater } from './completionupdater' import { ManagerWatcher } from './managerlib/managerwatcher' +import { inspectReadable } from '../utils/inspect' /** @@ -385,7 +386,7 @@ export class Manager { try { this.#rootFilePromise = rootFilePromise const wsfolders = vscode.workspace.workspaceFolders?.map(e => e.uri.toString(true)) - this.extension.logger.info(`Current workspace folders: ${JSON.stringify(wsfolders)}`) + this.extension.logger.info(`Current workspace folders: ${inspectReadable(wsfolders)}`) this.localRootFile = undefined const findMethods = [ () => this.finderUtils.findRootFromMagic(), diff --git a/src/components/managerlib/bibwatcher.ts b/src/components/managerlib/bibwatcher.ts index dac6e10d..7999f315 100644 --- a/src/components/managerlib/bibwatcher.ts +++ b/src/components/managerlib/bibwatcher.ts @@ -4,6 +4,7 @@ import { toKey } from '../../utils/tokey' import type { LwFileWatcher } from './lwfilewatcher' import type { Completer } from '../../providers/completion' import type { Logger } from '../logger' +import { inspectReadable } from '../../utils/inspect' export class BibWatcher { @@ -66,7 +67,7 @@ export class BibWatcher { } logWatchedFiles() { - this.extension.logger.debug(`BibWatcher.bibsWatched: ${JSON.stringify(Array.from(this.watchedBibs))}`) + this.extension.logger.debug(`BibWatcher.bibsWatched: ${inspectReadable(this.watchedBibs)}`) } } diff --git a/src/components/managerlib/managerwatcher.ts b/src/components/managerlib/managerwatcher.ts index fb108097..e5b05768 100644 --- a/src/components/managerlib/managerwatcher.ts +++ b/src/components/managerlib/managerwatcher.ts @@ -2,6 +2,7 @@ import * as vscode from 'vscode' import { toKey } from '../../utils/tokey' import type { LwFileWatcher } from './lwfilewatcher' import type { Logger } from '../logger' +import { inspectReadable } from '../../utils/inspect' export class ManagerWatcher { @@ -68,7 +69,7 @@ export class ManagerWatcher { } logWatchedFiles() { - this.extension.logger.debug(`ManagerWatcher.watchedFiles: ${JSON.stringify(Array.from(this.watchedFiles))}`) + this.extension.logger.debug(`ManagerWatcher.watchedFiles: ${inspectReadable(this.watchedFiles)}`) } } diff --git a/src/components/managerlib/pdfwatcher.ts b/src/components/managerlib/pdfwatcher.ts index ff5e9f08..0f1217d3 100644 --- a/src/components/managerlib/pdfwatcher.ts +++ b/src/components/managerlib/pdfwatcher.ts @@ -4,6 +4,7 @@ import type { LwFileWatcher } from './lwfilewatcher' import type { Logger } from '../logger' import type { Viewer } from '../viewer' import { sleep } from '../../utils/utils' +import { inspectReadable } from '../../utils/inspect' export class PdfWatcher { @@ -65,8 +66,8 @@ export class PdfWatcher { } logWatchedFiles() { - this.extension.logger.debug(`PdfWatcher.pdfsWatched: ${JSON.stringify(Array.from(this.watchedPdfs))}`) - this.extension.logger.debug(`PdfWatcher.ignoredPdfUris: ${JSON.stringify(Array.from(this.ignoredPdfUris))}`) + this.extension.logger.debug(`PdfWatcher.pdfsWatched: ${inspectReadable(this.watchedPdfs)}`) + this.extension.logger.debug(`PdfWatcher.ignoredPdfUris: ${inspectReadable(this.ignoredPdfUris)}`) } } diff --git a/src/components/server.ts b/src/components/server.ts index 6ba934ce..3ab3e06d 100644 --- a/src/components/server.ts +++ b/src/components/server.ts @@ -10,6 +10,7 @@ import { readFileAsBuffer } from '../lib/lwfs/lwfs' import { ExternalPromise } from '../utils/externalpromise' import type { Logger } from './logger' import type { Viewer } from './viewer' +import { inspectCompact, inspectReadable } from '../utils/inspect' class WsServer extends ws.Server { private readonly validOrigin: string @@ -32,7 +33,7 @@ class WsServer extends ws.Server { shouldHandle(req: http.IncomingMessage): boolean { const reqOrigin = req.headers['origin'] if (reqOrigin !== undefined && reqOrigin !== this.validOrigin) { - this.extension.logger.info(`[Server] Origin in WebSocket upgrade request is invalid: ${JSON.stringify(req.headers)}`) + this.extension.logger.info(`[Server] Origin in WebSocket upgrade request is invalid: ${inspectReadable(req.headers)}`) this.extension.logger.info(`[Server] Valid origin: ${this.validOrigin}`) return false } else { @@ -96,17 +97,17 @@ export class Server { const address = this.httpServer.address() if (address && typeof address !== 'string') { this.address = address - this.extension.logger.info(`[Server] Server successfully started: ${JSON.stringify(address)}`) + this.extension.logger.info(`[Server] Server successfully started: ${inspectCompact(address)}`) this.validOriginUri = await this.obtainValidOrigin(address.port) this.extension.logger.info(`[Server] valdOrigin is ${this.validOrigin}`) this.initializeWsServer() this.#serverStarted.resolve() } else { - this.extension.logger.error(`[Server] Server failed to start. Address is invalid: ${JSON.stringify(address)}`) + this.extension.logger.error(`[Server] Server failed to start. Address is invalid: ${inspectCompact(address)}`) } }) this.httpServer.on('error', (err) => { - this.extension.logger.error(`[Server] Error creating LaTeX Toybox http server: ${JSON.stringify(err)}.`) + this.extension.logger.error(`[Server] Error creating LaTeX Toybox http server: ${inspectReadable(err)}.`) }) } @@ -120,7 +121,7 @@ export class Server { const wsServer = new WsServer(this.httpServer, this.extension, this.validOrigin) wsServer.on('connection', (websocket) => { websocket.on('message', (msg: string) => this.extension.viewer.handler(websocket, msg)) - websocket.on('error', (err) => this.extension.logger.error(`[Server] Error on WebSocket connection. ${JSON.stringify(err)}`)) + websocket.on('error', (err) => this.extension.logger.error(`[Server] Error on WebSocket connection. ${inspectReadable(err)}`)) }) } @@ -133,7 +134,7 @@ export class Server { private checkHttpOrigin(req: http.IncomingMessage, response: http.ServerResponse): boolean { const reqOrigin = req.headers['origin'] if (reqOrigin !== undefined && reqOrigin !== this.validOrigin) { - this.extension.logger.info(`[Server] Origin in http request is invalid: ${JSON.stringify(req.headers)}`) + this.extension.logger.info(`[Server] Origin in http request is invalid: ${inspectReadable(req.headers)}`) this.extension.logger.info(`[Server] Valid origin: ${this.validOrigin}`) response.writeHead(403) response.end() diff --git a/src/components/viewer.ts b/src/components/viewer.ts index b18d2f77..192298ae 100644 --- a/src/components/viewer.ts +++ b/src/components/viewer.ts @@ -3,15 +3,15 @@ import type ws from 'ws' import * as path from 'path' import * as cs from 'cross-spawn' -import type {Locator, SyncTeXRecordForward} from './locator' -import {openWebviewPanel} from '../utils/webview' -import {getCurrentThemeLightness} from '../utils/theme' +import type { Locator, SyncTeXRecordForward } from './locator' +import { openWebviewPanel } from '../utils/webview' +import { getCurrentThemeLightness } from '../utils/theme' -import type {ClientRequest, PdfViewerParams, PdfViewerState} from '../../types/latex-toybox-protocol-types/index' +import type { ClientRequest, PdfViewerParams, PdfViewerState } from '../../types/latex-toybox-protocol-types/index' -import {Client} from './viewerlib/client' -import {PdfViewerPanel, PdfViewerPanelSerializer, PdfViewerPanelService} from './viewerlib/pdfviewerpanel' -import {PdfViewerManagerService} from './viewerlib/pdfviewermanager' +import { Client } from './viewerlib/client' +import { PdfViewerPanel, PdfViewerPanelSerializer, PdfViewerPanelService } from './viewerlib/pdfviewerpanel' +import { PdfViewerManagerService } from './viewerlib/pdfviewermanager' import * as lwfs from '../lib/lwfs/lwfs' import { encodePathWithPrefix } from '../utils/encodepdffilepath' import type { EventBus } from './eventbus' @@ -20,7 +20,8 @@ import type { Manager } from './manager' import type { Server } from './server' import type { LwStatusBarItem } from './statusbaritem' import { ExternalPromise } from '../utils/externalpromise' -export {PdfViewerHookProvider} from './viewerlib/pdfviewerhook' +import { inspectCompact } from '../utils/inspect' +export { PdfViewerHookProvider } from './viewerlib/pdfviewerhook' export class Viewer { @@ -100,7 +101,7 @@ export class Viewer { * refreshes all the PDF viewers. */ refreshExistingViewer(sourceFile?: string, pdfFileUri?: vscode.Uri): void { - this.extension.logger.info(`Call refreshExistingViewer: ${JSON.stringify({sourceFile})}`) + this.extension.logger.info(`Call refreshExistingViewer: ${inspectCompact({sourceFile})}`) const pdfFile = pdfFileUri || (sourceFile ? this.tex2pdf(sourceFile, true) : undefined) if (pdfFile === undefined) { this.clientMap.forEach(clientSet => { diff --git a/src/components/viewerlib/pdfviewerpanel.ts b/src/components/viewerlib/pdfviewerpanel.ts index cc247d36..37abec32 100644 --- a/src/components/viewerlib/pdfviewerpanel.ts +++ b/src/components/viewerlib/pdfviewerpanel.ts @@ -10,6 +10,7 @@ import { encodePathWithPrefix } from '../../utils/encodepdffilepath' import { EventBus } from '../eventbus' import { Logger } from '../logger' import { Server } from '../server' +import { inspectCompact } from '../../utils/inspect' export class PdfViewerPanel { @@ -81,7 +82,7 @@ export class PdfViewerPanelSerializer implements vscode.WebviewPanelSerializer { localResourceRoots: [vscode.Uri.file(resourceFolder)] } await this.extension.server.serverStarted - this.extension.logger.info(`Restoring the PDF viewer at the column ${panel.viewColumn} from the state: ${JSON.stringify(argState)}`) + this.extension.logger.info(`Restoring the PDF viewer at the column ${panel.viewColumn} from the state: ${inspectCompact(argState)}`) const state = argState.state let pdfFileUri: vscode.Uri | undefined if (state.path) { diff --git a/src/providers/completionlib/command.ts b/src/providers/completionlib/command.ts index 6849f309..6d89df8d 100644 --- a/src/providers/completionlib/command.ts +++ b/src/providers/completionlib/command.ts @@ -10,6 +10,7 @@ import type { Completer } from '../completion' import type { Logger } from '../../components/logger' import type { Manager } from '../../components/manager' import { CommandKind } from './completionkind' +import { inspectCompact } from '../../utils/inspect' type DataUnimathSymbolsJsonType = typeof import('../../../data/unimathsymbols.json') @@ -178,7 +179,7 @@ export class Command implements IProvider, ICommand { pkgEntry.push(this.entryCmdToCompletion(key, cmds[key])) } else { this.extension.logger.info(`Cannot parse intellisense file: ${filePathUri}`) - this.extension.logger.info(`Missing field in entry: "${key}": ${JSON.stringify(cmds[key])}`) + this.extension.logger.info(`Missing field in entry: "${key}": ${inspectCompact(cmds[key])}`) } }) } catch (e) { diff --git a/src/providers/completionlib/environment.ts b/src/providers/completionlib/environment.ts index 8975ec26..12b607f5 100644 --- a/src/providers/completionlib/environment.ts +++ b/src/providers/completionlib/environment.ts @@ -9,6 +9,7 @@ import type { Logger } from '../../components/logger' import type { Manager } from '../../components/manager' import type { Completer } from '../completion' import { EnvAsCmdKind, EnvKind } from './completionkind' +import { inspectCompact } from '../../utils/inspect' type DataEnvsJsonType = typeof import('../../../data/environments.json') @@ -73,7 +74,7 @@ export class Environment implements IProvider { Object.keys(envs).forEach(key => { if (! isEnvItemEntry(envs[key])) { this.extension.logger.info(`Cannot parse intellisense file: ${filePathUri}`) - this.extension.logger.info(`Missing field in entry: "${key}": ${JSON.stringify(envs[key])}`) + this.extension.logger.info(`Missing field in entry: "${key}": ${inspectCompact(envs[key])}`) delete envs[key] } }) diff --git a/src/providersmanager.ts b/src/providersmanager.ts index a23fa67d..2f833046 100644 --- a/src/providersmanager.ts +++ b/src/providersmanager.ts @@ -14,6 +14,7 @@ import { BibtexFormatterProvider } from './providers/bibtexformatter' import type { Extension } from './main' import { MathPreviewPanelSerializer } from './components/mathpreviewpanel' import { AtSuggestionCompleter } from './providers/atsuggestion' +import { inspectCompact } from './utils/inspect' abstract class SingleProviderManager implements vscode.Disposable { @@ -74,7 +75,7 @@ export class ProvidersManager { const configuration = vscode.workspace.getConfiguration('latex-toybox') const userTriggersLatex = configuration.get('intellisense.triggers.latex', ['{']) const latexTriggers = ['\\', ','].concat(userTriggersLatex) - extension.logger.info(`Trigger characters for intellisense of LaTeX documents: ${JSON.stringify(latexTriggers)}`) + extension.logger.info(`Trigger characters for intellisense of LaTeX documents: ${inspectCompact(latexTriggers)}`) return vscode.languages.registerCompletionItemProvider(latexDoctexSelector, extension.completer, ...latexTriggers) } }, diff --git a/src/utils/inspect.ts b/src/utils/inspect.ts new file mode 100644 index 00000000..16778d8e --- /dev/null +++ b/src/utils/inspect.ts @@ -0,0 +1,9 @@ +import { inspect } from 'util' + +export function inspectReadable(obj: unknown): string { + return inspect(obj, { compact: false, depth: null, breakLength: Infinity }) +} + +export function inspectCompact(obj: unknown): string { + return inspect(obj, { compact: true, depth: null, breakLength: Infinity }) +}