Skip to content

Commit

Permalink
Uset util.inspect() instead of JSON.stringify() for logging.
Browse files Browse the repository at this point in the history
  • Loading branch information
tamuratak committed Oct 1, 2023
1 parent 17bda6b commit d6ace1d
Show file tree
Hide file tree
Showing 17 changed files with 59 additions and 34 deletions.
3 changes: 2 additions & 1 deletion src/components/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion src/components/configuration.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as vscode from 'vscode'
import { Logger } from './logger'
import { inspectReadable } from '../utils/inspect'


export class Configuration {
Expand Down Expand Up @@ -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)}`)
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/components/eventbus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' |
Expand Down Expand Up @@ -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)}`)
})
})
}
Expand Down
5 changes: 3 additions & 2 deletions src/components/locator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -177,7 +178,7 @@ export class Locator {
private invokeSyncTeXCommandForward(line: number, col: number, filePath: string, pdfFile: string): Thenable<SyncTeXRecordForward> {
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)})
Expand Down Expand Up @@ -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)})
Expand Down
9 changes: 5 additions & 4 deletions src/components/locatorlib/synctex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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}`)
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion src/components/logger.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as vscode from 'vscode'
import { ILogger } from '../interfaces'
import { inspectCompact } from '../utils/inspect'


export class Logger implements ILogger {
Expand All @@ -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) {
Expand Down
3 changes: 2 additions & 1 deletion src/components/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'


/**
Expand Down Expand Up @@ -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(),
Expand Down
3 changes: 2 additions & 1 deletion src/components/managerlib/bibwatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)}`)
}

}
3 changes: 2 additions & 1 deletion src/components/managerlib/managerwatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)}`)
}

}
5 changes: 3 additions & 2 deletions src/components/managerlib/pdfwatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)}`)
}

}
13 changes: 7 additions & 6 deletions src/components/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Expand Down Expand Up @@ -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)}.`)
})
}

Expand All @@ -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)}`))
})
}

Expand All @@ -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()
Expand Down
19 changes: 10 additions & 9 deletions src/components/viewer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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 {
Expand Down Expand Up @@ -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 => {
Expand Down
3 changes: 2 additions & 1 deletion src/components/viewerlib/pdfviewerpanel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down
3 changes: 2 additions & 1 deletion src/providers/completionlib/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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) {
Expand Down
3 changes: 2 additions & 1 deletion src/providers/completionlib/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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]
}
})
Expand Down
3 changes: 2 additions & 1 deletion src/providersmanager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}
},
Expand Down
9 changes: 9 additions & 0 deletions src/utils/inspect.ts
Original file line number Diff line number Diff line change
@@ -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 })
}

0 comments on commit d6ace1d

Please sign in to comment.