diff --git a/src/annotations/gutterBlameAnnotationProvider.ts b/src/annotations/gutterBlameAnnotationProvider.ts index edbf198..acbc6ed 100644 --- a/src/annotations/gutterBlameAnnotationProvider.ts +++ b/src/annotations/gutterBlameAnnotationProvider.ts @@ -5,9 +5,8 @@ import type { Container } from '../container'; import { CommitFormatOptions, CommitFormatter } from '../git/formatters/commitFormatter'; import type { GitBlame } from '../git/models/blame'; import type { GitCommit } from '../git/models/commit'; -import { Logger } from '../logger'; import { filterMap } from '../system/array'; -import { log } from '../system/decorators/log'; +import { getLogScope, log } from '../system/decorators/log'; import { first } from '../system/iterable'; import { Stopwatch } from '../system/stopwatch'; import { getTokensFromTemplate, getWidth, TokenOptions } from '../system/string'; @@ -37,14 +36,14 @@ export class GutterBlameAnnotationProvider extends BlameAnnotationProviderBase { @log() async onProvideAnnotation(context?: AnnotationContext, _type?: FileAnnotationType): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); this.annotationContext = context; const blame = await this.getBlame(); if (blame == null) return false; - const sw = new Stopwatch(cc!); + const sw = new Stopwatch(scope); const cfg = configuration.get('blame'); diff --git a/src/annotations/gutterChangesAnnotationProvider.ts b/src/annotations/gutterChangesAnnotationProvider.ts index 8a32090..89adbbd 100644 --- a/src/annotations/gutterChangesAnnotationProvider.ts +++ b/src/annotations/gutterChangesAnnotationProvider.ts @@ -17,8 +17,7 @@ import type { Container } from '../container'; import type { GitCommit } from '../git/models/commit'; import type { GitDiff } from '../git/models/diff'; import { Hovers } from '../hovers/hovers'; -import { Logger } from '../logger'; -import { log } from '../system/decorators/log'; +import { getLogScope, log } from '../system/decorators/log'; import { Stopwatch } from '../system/stopwatch'; import type { GitDocumentState, TrackedDocument } from '../trackers/gitDocumentTracker'; import { AnnotationContext, AnnotationProviderBase } from './annotationProvider'; @@ -66,7 +65,7 @@ export class GutterChangesAnnotationProvider extends AnnotationProviderBase { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); if (this.mustReopen(context)) { this.clear(); @@ -159,7 +158,7 @@ export class GutterChangesAnnotationProvider extends AnnotationProviderBase(d?: T): d is T => Boolean(d)); if (!diffs?.length) return false; - const sw = new Stopwatch(cc!); + const sw = new Stopwatch(scope); const decorationsMap = new Map< string, diff --git a/src/annotations/gutterHeatmapBlameAnnotationProvider.ts b/src/annotations/gutterHeatmapBlameAnnotationProvider.ts index a2dfabd..cc6d031 100644 --- a/src/annotations/gutterHeatmapBlameAnnotationProvider.ts +++ b/src/annotations/gutterHeatmapBlameAnnotationProvider.ts @@ -2,8 +2,7 @@ import { Range, TextEditor, TextEditorDecorationType } from 'vscode'; import { FileAnnotationType } from '../configuration'; import type { Container } from '../container'; import type { GitCommit } from '../git/models/commit'; -import { Logger } from '../logger'; -import { log } from '../system/decorators/log'; +import { getLogScope, log } from '../system/decorators/log'; import { Stopwatch } from '../system/stopwatch'; import type { GitDocumentState } from '../trackers/gitDocumentTracker'; import type { TrackedDocument } from '../trackers/trackedDocument'; @@ -18,14 +17,14 @@ export class GutterHeatmapBlameAnnotationProvider extends BlameAnnotationProvide @log() async onProvideAnnotation(context?: AnnotationContext, _type?: FileAnnotationType): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); this.annotationContext = context; const blame = await this.getBlame(); if (blame == null) return false; - const sw = new Stopwatch(cc!); + const sw = new Stopwatch(scope); const decorationsMap = new Map< string, diff --git a/src/annotations/lineAnnotationController.ts b/src/annotations/lineAnnotationController.ts index b7cc0d1..7c0ec63 100644 --- a/src/annotations/lineAnnotationController.ts +++ b/src/annotations/lineAnnotationController.ts @@ -17,8 +17,8 @@ import { CommitFormatter } from '../git/formatters/commitFormatter'; import type { GitCommit } from '../git/models/commit'; import type { PullRequest } from '../git/models/pullRequest'; import { Authentication } from '../git/remotes/provider'; -import { LogCorrelationContext, Logger } from '../logger'; -import { debug, log } from '../system/decorators/log'; +import { Logger, LogScope } from '../logger'; +import { debug, getLogScope, log } from '../system/decorators/log'; import { once } from '../system/event'; import { count, every, filterMap } from '../system/iterable'; import { PromiseCancelledError, PromiseCancelledErrorWithId, raceAll } from '../system/promise'; @@ -189,12 +189,12 @@ export class LineAnnotationController implements Disposable { private async refresh(editor: TextEditor | undefined, options?: { prs?: Map }) { if (editor == null && this._editor == null) return; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const selections = this.container.lineTracker.selections; if (editor == null || selections == null || !isTextEditor(editor)) { - if (cc != null) { - cc.exitDetails = ` ${GlyphChars.Dot} Skipped because there is no valid editor or no valid selections`; + if (scope != null) { + scope.exitDetails = ` ${GlyphChars.Dot} Skipped because there is no valid editor or no valid selections`; } this.clear(this._editor); @@ -210,8 +210,8 @@ export class LineAnnotationController implements Disposable { const cfg = configuration.get('currentLine'); if (this.suspended) { - if (cc != null) { - cc.exitDetails = ` ${GlyphChars.Dot} Skipped because the controller is suspended`; + if (scope != null) { + scope.exitDetails = ` ${GlyphChars.Dot} Skipped because the controller is suspended`; } this.clear(editor); @@ -220,8 +220,8 @@ export class LineAnnotationController implements Disposable { const trackedDocument = await this.container.tracker.getOrAdd(editor.document); if (!trackedDocument.isBlameable && this.suspended) { - if (cc != null) { - cc.exitDetails = ` ${GlyphChars.Dot} Skipped because the ${ + if (scope != null) { + scope.exitDetails = ` ${GlyphChars.Dot} Skipped because the ${ this.suspended ? 'controller is suspended' : `document(${trackedDocument.uri.toString(true)}) is not blameable` @@ -234,8 +234,8 @@ export class LineAnnotationController implements Disposable { // Make sure the editor hasn't died since the await above and that we are still on the same line(s) if (editor.document == null || !this.container.lineTracker.includes(selections)) { - if (cc != null) { - cc.exitDetails = ` ${GlyphChars.Dot} Skipped because the ${ + if (scope != null) { + scope.exitDetails = ` ${GlyphChars.Dot} Skipped because the ${ editor.document == null ? 'editor is gone' : `selection(s)=${selections @@ -246,8 +246,8 @@ export class LineAnnotationController implements Disposable { return; } - if (cc != null) { - cc.exitDetails = ` ${GlyphChars.Dot} selection(s)=${selections + if (scope != null) { + scope.exitDetails = ` ${GlyphChars.Dot} selection(s)=${selections .map(s => `[${s.anchor}-${s.active}]`) .join()}`; } @@ -256,7 +256,7 @@ export class LineAnnotationController implements Disposable { ...filterMap(selections, selection => { const state = this.container.lineTracker.getState(selection.active); if (state?.commit == null) { - Logger.debug(cc, `Line ${selection.active} returned no commit`); + Logger.debug(scope, `Line ${selection.active} returned no commit`); return undefined; } @@ -292,7 +292,7 @@ export class LineAnnotationController implements Disposable { if (prs != null) { this._cancellation?.cancel(); this._cancellation = new CancellationTokenSource(); - void this.waitForAnyPendingPullRequests(editor, prs, this._cancellation.token, timeout, cc); + void this.waitForAnyPendingPullRequests(editor, prs, this._cancellation.token, timeout, scope); } const decorations = []; @@ -344,13 +344,13 @@ export class LineAnnotationController implements Disposable { >, cancellationToken: CancellationToken, timeout: number, - cc: LogCorrelationContext | undefined, + scope: LogScope | undefined, ) { // If there are any PRs that timed out, refresh the annotation(s) once they complete const prCount = count(prs.values(), pr => pr instanceof PromiseCancelledError); if (cancellationToken.isCancellationRequested || prCount === 0) return; - Logger.debug(cc, `${GlyphChars.Dot} ${prCount} pull request queries took too long (over ${timeout} ms)`); + Logger.debug(scope, `${GlyphChars.Dot} ${prCount} pull request queries took too long (over ${timeout} ms)`); const resolved = new Map(); for (const [key, value] of prs) { @@ -359,7 +359,7 @@ export class LineAnnotationController implements Disposable { if (cancellationToken.isCancellationRequested || editor !== this._editor) return; - Logger.debug(cc, `${GlyphChars.Dot} ${prCount} pull request queries completed; refreshing...`); + Logger.debug(scope, `${GlyphChars.Dot} ${prCount} pull request queries completed; refreshing...`); void this.refresh(editor, { prs: resolved }); } diff --git a/src/commands/gitCommands.ts b/src/commands/gitCommands.ts index d99058a..12b729f 100644 --- a/src/commands/gitCommands.ts +++ b/src/commands/gitCommands.ts @@ -116,7 +116,7 @@ export class GitCommandsCommand extends Command { return this.execute(args); } - @log({ args: false, correlate: true, singleLine: true, timed: false }) + @log({ args: false, scoped: true, singleLine: true, timed: false }) async execute(args?: GitCommandsCommandArgs) { const commandsStep = new PickCommandStep(this.container, args); diff --git a/src/commands/switchMode.ts b/src/commands/switchMode.ts index 9e263f9..ac2a7fb 100644 --- a/src/commands/switchMode.ts +++ b/src/commands/switchMode.ts @@ -2,10 +2,9 @@ import { ConfigurationTarget } from 'vscode'; import { configuration } from '../configuration'; import { Commands } from '../constants'; import type { Container } from '../container'; -import { Logger } from '../logger'; import { ModePicker } from '../quickpicks/modePicker'; import { command } from '../system/command'; -import { log } from '../system/decorators/log'; +import { getLogScope, log } from '../system/decorators/log'; import { Command } from './base'; @command() @@ -14,15 +13,15 @@ export class SwitchModeCommand extends Command { super(Commands.SwitchMode); } - @log({ args: false, correlate: true, singleLine: true, timed: false }) + @log({ args: false, scoped: true, singleLine: true, timed: false }) async execute() { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const pick = await ModePicker.show(); if (pick === undefined) return; - if (cc != null) { - cc.exitDetails = ` \u2014 mode=${pick.key ?? ''}`; + if (scope != null) { + scope.exitDetails = ` \u2014 mode=${pick.key ?? ''}`; } const active = configuration.get('mode.active'); diff --git a/src/env/node/git/localGitProvider.ts b/src/env/node/git/localGitProvider.ts index 8a7a9ec..1f90eb6 100644 --- a/src/env/node/git/localGitProvider.ts +++ b/src/env/node/git/localGitProvider.ts @@ -90,13 +90,13 @@ import { GitWorktreeParser } from '../../../git/parsers/worktreeParser'; import { RemoteProviderFactory, RemoteProviders } from '../../../git/remotes/factory'; import { RemoteProvider, RemoteResourceType, RichRemoteProvider } from '../../../git/remotes/provider'; import { SearchPattern } from '../../../git/search'; -import { LogCorrelationContext, Logger } from '../../../logger'; +import { Logger, LogScope } from '../../../logger'; import { Messages } from '../../../messages'; import { WorkspaceStorageKeys } from '../../../storage'; import { countStringLength, filterMap } from '../../../system/array'; import { TimedCancellationSource } from '../../../system/cancellation'; import { gate } from '../../../system/decorators/gate'; -import { debug, log } from '../../../system/decorators/log'; +import { debug, getLogScope, log } from '../../../system/decorators/log'; import { filterMap as filterMapIterable, find, first, last, some } from '../../../system/iterable'; import { commonBaseIndex, @@ -240,10 +240,10 @@ export class LocalGitProvider implements GitProvider, Disposable { @log() private async findGit(): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); if (!configuration.getAny('git.enabled', null, true)) { - Logger.log(cc, 'Built-in Git is disabled ("git.enabled": false)'); + Logger.log(scope, 'Built-in Git is disabled ("git.enabled": false)'); void Messages.showGitDisabledErrorMessage(); throw new UnableToFindGitError(); @@ -295,13 +295,13 @@ export class LocalGitProvider implements GitProvider, Disposable { void this.container.storage.storeWorkspace(WorkspaceStorageKeys.GitPath, location.path); }, 1000); - if (cc != null) { - cc.exitDetails = ` ${GlyphChars.Dot} Git (${location.version}) found in ${ + if (scope != null) { + scope.exitDetails = ` ${GlyphChars.Dot} Git (${location.version}) found in ${ location.path === 'git' ? 'PATH' : location.path }`; } else { Logger.log( - cc, + scope, `Git (${location.version}) found in ${location.path === 'git' ? 'PATH' : location.path} ${ GlyphChars.Dot } ${getDurationMilliseconds(start)} ms`, @@ -310,7 +310,7 @@ export class LocalGitProvider implements GitProvider, Disposable { // Warn if git is less than v2.7.2 if (compare(fromString(location.version), fromString('2.7.2')) === -1) { - Logger.log(cc, `Git version (${location.version}) is outdated`); + Logger.log(scope, `Git version (${location.version}) is outdated`); void Messages.showGitVersionUnsupportedErrorMessage(location.version, '2.7.2'); } @@ -501,13 +501,13 @@ export class LocalGitProvider implements GitProvider, Disposable { }`, }) private async repositorySearch(folder: WorkspaceFolder, depth?: number): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); depth = depth ?? configuration.get('advanced.repositorySearchDepth', folder.uri) ?? configuration.getAny(CoreGitConfiguration.RepositoryScanMaxDepth, folder.uri, 1); - Logger.log(cc, `searching (depth=${depth})...`); + Logger.log(scope, `searching (depth=${depth})...`); const repositories: Repository[] = []; @@ -523,7 +523,7 @@ export class LocalGitProvider implements GitProvider, Disposable { canonicalRootPath = normalizePath(canonicalUri.fsPath); } - Logger.log(cc, `found root repository in '${uri.fsPath}'`); + Logger.log(scope, `found root repository in '${uri.fsPath}'`); repositories.push(...this.openRepository(folder, uri, true)); } @@ -554,9 +554,9 @@ export class LocalGitProvider implements GitProvider, Disposable { } catch (ex) { const msg: string = ex?.toString() ?? ''; if (RepoSearchWarnings.doesNotExist.test(msg)) { - Logger.log(cc, `FAILED${msg ? ` Error: ${msg}` : ''}`); + Logger.log(scope, `FAILED${msg ? ` Error: ${msg}` : ''}`); } else { - Logger.error(ex, cc, 'FAILED'); + Logger.error(ex, scope, 'FAILED'); } return repositories; @@ -576,16 +576,16 @@ export class LocalGitProvider implements GitProvider, Disposable { continue; } - Logger.log(cc, `searching in '${p}'...`); + Logger.log(scope, `searching in '${p}'...`); Logger.debug( - cc, + scope, `normalizedRepoPath=${normalized}, rootPath=${rootPath}, canonicalRootPath=${canonicalRootPath}`, ); const rp = await this.findRepositoryUri(Uri.file(p), true); if (rp == null) continue; - Logger.log(cc, `found repository in '${rp.fsPath}'`); + Logger.log(scope, `found repository in '${rp.fsPath}'`); repositories.push(...this.openRepository(folder, rp, false)); } @@ -599,7 +599,7 @@ export class LocalGitProvider implements GitProvider, Disposable { excludes: Set, repositories: string[] = [], ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); return new Promise((resolve, reject) => { readdir(root, { withFileTypes: true }, async (err, files) => { @@ -623,7 +623,7 @@ export class LocalGitProvider implements GitProvider, Disposable { try { await this.repositorySearchCore(resolvePath(root, f.name), depth, excludes, repositories); } catch (ex) { - Logger.error(ex, cc, 'FAILED'); + Logger.error(ex, scope, 'FAILED'); } } } @@ -809,7 +809,7 @@ export class LocalGitProvider implements GitProvider, Disposable { @log() async applyChangesToWorkingFile(uri: GitUri, ref1?: string, ref2?: string) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); ref1 = ref1 ?? uri.sha; if (ref1 == null || uri.repoPath == null) return; @@ -848,7 +848,7 @@ export class LocalGitProvider implements GitProvider, Disposable { } } - Logger.error(ex, cc); + Logger.error(ex, scope); void Messages.showGenericErrorMessage('Unable to apply changes'); } } @@ -859,7 +859,7 @@ export class LocalGitProvider implements GitProvider, Disposable { ref: string, options?: { createBranch?: string } | { path?: string }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { await this.git.checkout(repoPath, ref, options); @@ -872,7 +872,7 @@ export class LocalGitProvider implements GitProvider, Disposable { return; } - Logger.error(ex, cc); + Logger.error(ex, scope); void void Messages.showGenericErrorMessage(`Unable to checkout '${ref}'`); } } @@ -952,7 +952,7 @@ export class LocalGitProvider implements GitProvider, Disposable { @gate() @debug() async findRepositoryUri(uri: Uri, isDirectory?: boolean): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); let repoPath: string | undefined; try { @@ -1007,13 +1007,13 @@ export class LocalGitProvider implements GitProvider, Disposable { [repoPath, symlink] = await new Promise<[string, string | undefined]>(resolve => { realpath(uri.fsPath, { encoding: 'utf8' }, (err, resolvedPath) => { if (err != null) { - Logger.debug(cc, `fs.realpath failed; repoPath=${repoPath}`); + Logger.debug(scope, `fs.realpath failed; repoPath=${repoPath}`); resolve([repoPath!, undefined]); return; } if (equalsIgnoreCase(uri.fsPath, resolvedPath)) { - Logger.debug(cc, `No symlink detected; repoPath=${repoPath}`); + Logger.debug(scope, `No symlink detected; repoPath=${repoPath}`); resolve([repoPath!, undefined]); return; } @@ -1028,7 +1028,7 @@ export class LocalGitProvider implements GitProvider, Disposable { } Logger.debug( - cc, + scope, `Symlink detected; repoPath=${repoPath}, path=${uri.fsPath}, resolvedPath=${resolvedPath}`, ); resolve([repoPath!, linkPath]); @@ -1044,7 +1044,7 @@ export class LocalGitProvider implements GitProvider, Disposable { return repoPath ? Uri.file(repoPath) : undefined; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); return undefined; } } @@ -1060,7 +1060,7 @@ export class LocalGitProvider implements GitProvider, Disposable { @gate((u, d) => `${u.toString()}|${d?.isDirty}`) @log({ args: { 1: d => d?.isDirty } }) async getBlame(uri: GitUri, document?: TextDocument | undefined): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); if (document?.isDirty) return this.getBlameContents(uri, document.getText()); @@ -1074,22 +1074,22 @@ export class LocalGitProvider implements GitProvider, Disposable { if (doc.state != null) { const cachedBlame = doc.state.getBlame(key); if (cachedBlame != null) { - Logger.debug(cc, `Cache hit: '${key}'`); + Logger.debug(scope, `Cache hit: '${key}'`); return cachedBlame.item; } } - Logger.debug(cc, `Cache miss: '${key}'`); + Logger.debug(scope, `Cache miss: '${key}'`); if (doc.state == null) { doc.state = new GitDocumentState(); } } - const promise = this.getBlameCore(uri, doc, key, cc); + const promise = this.getBlameCore(uri, doc, key, scope); if (doc.state != null) { - Logger.debug(cc, `Cache add: '${key}'`); + Logger.debug(scope, `Cache add: '${key}'`); const value: CachedBlame = { item: promise as Promise, @@ -1104,11 +1104,11 @@ export class LocalGitProvider implements GitProvider, Disposable { uri: GitUri, document: TrackedDocument, key: string, - cc: LogCorrelationContext | undefined, + scope: LogScope | undefined, ): Promise { const paths = await this.isTrackedPrivate(uri); if (paths == null) { - Logger.log(cc, `Skipping blame; '${uri.fsPath}' is not tracked`); + Logger.log(scope, `Skipping blame; '${uri.fsPath}' is not tracked`); return emptyPromise as Promise; } @@ -1125,7 +1125,7 @@ export class LocalGitProvider implements GitProvider, Disposable { // Trap and cache expected blame errors if (document.state != null) { const msg = ex?.toString() ?? ''; - Logger.debug(cc, `Cache replace (with empty promise): '${key}'`); + Logger.debug(scope, `Cache replace (with empty promise): '${key}'`); const value: CachedBlame = { item: emptyPromise as Promise, @@ -1144,7 +1144,7 @@ export class LocalGitProvider implements GitProvider, Disposable { @log({ args: { 1: '' } }) async getBlameContents(uri: GitUri, contents: string): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const key = `blame:${md5(contents)}`; @@ -1153,22 +1153,22 @@ export class LocalGitProvider implements GitProvider, Disposable { if (doc.state != null) { const cachedBlame = doc.state.getBlame(key); if (cachedBlame != null) { - Logger.debug(cc, `Cache hit: ${key}`); + Logger.debug(scope, `Cache hit: ${key}`); return cachedBlame.item; } } - Logger.debug(cc, `Cache miss: ${key}`); + Logger.debug(scope, `Cache miss: ${key}`); if (doc.state == null) { doc.state = new GitDocumentState(); } } - const promise = this.getBlameContentsCore(uri, contents, doc, key, cc); + const promise = this.getBlameContentsCore(uri, contents, doc, key, scope); if (doc.state != null) { - Logger.debug(cc, `Cache add: '${key}'`); + Logger.debug(scope, `Cache add: '${key}'`); const value: CachedBlame = { item: promise as Promise, @@ -1184,11 +1184,11 @@ export class LocalGitProvider implements GitProvider, Disposable { contents: string, document: TrackedDocument, key: string, - cc: LogCorrelationContext | undefined, + scope: LogScope | undefined, ): Promise { const paths = await this.isTrackedPrivate(uri); if (paths == null) { - Logger.log(cc, `Skipping blame; '${uri.fsPath}' is not tracked`); + Logger.log(scope, `Skipping blame; '${uri.fsPath}' is not tracked`); return emptyPromise as Promise; } @@ -1206,7 +1206,7 @@ export class LocalGitProvider implements GitProvider, Disposable { // Trap and cache expected blame errors if (document.state != null) { const msg = ex?.toString() ?? ''; - Logger.debug(cc, `Cache replace (with empty promise): '${key}'`); + Logger.debug(scope, `Cache replace (with empty promise): '${key}'`); const value: CachedBlame = { item: emptyPromise as Promise, @@ -1561,7 +1561,7 @@ export class LocalGitProvider implements GitProvider, Disposable { uri: Uri, options?: { ref?: string; firstIfNotFound?: boolean; range?: Range }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const [relativePath, root] = splitPath(uri, repoPath); @@ -1584,7 +1584,7 @@ export class LocalGitProvider implements GitProvider, Disposable { return commit ?? first(log.commits.values()); } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); return undefined; } } @@ -1712,7 +1712,7 @@ export class LocalGitProvider implements GitProvider, Disposable { async getCurrentUser(repoPath: string): Promise { if (!repoPath) return undefined; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const repo = this._repoInfoCache.get(repoPath); @@ -1767,7 +1767,7 @@ export class LocalGitProvider implements GitProvider, Disposable { this._repoInfoCache.set(repoPath, { ...repo, user: user }); return user; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; // Mark it so we won't bother trying again @@ -1804,7 +1804,7 @@ export class LocalGitProvider implements GitProvider, Disposable { @log() async getDiffForFile(uri: GitUri, ref1: string | undefined, ref2?: string): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); let key = 'diff'; if (ref1 != null) { @@ -1819,12 +1819,12 @@ export class LocalGitProvider implements GitProvider, Disposable { if (doc.state != null) { const cachedDiff = doc.state.getDiff(key); if (cachedDiff != null) { - Logger.debug(cc, `Cache hit: '${key}'`); + Logger.debug(scope, `Cache hit: '${key}'`); return cachedDiff.item; } } - Logger.debug(cc, `Cache miss: '${key}'`); + Logger.debug(scope, `Cache miss: '${key}'`); if (doc.state == null) { doc.state = new GitDocumentState(); @@ -1839,11 +1839,11 @@ export class LocalGitProvider implements GitProvider, Disposable { { encoding: GitProviderService.getEncoding(uri) }, doc, key, - cc, + scope, ); if (doc.state != null) { - Logger.debug(cc, `Cache add: '${key}'`); + Logger.debug(scope, `Cache add: '${key}'`); const value: CachedDiff = { item: promise as Promise, @@ -1862,7 +1862,7 @@ export class LocalGitProvider implements GitProvider, Disposable { options: { encoding?: string }, document: TrackedDocument, key: string, - cc: LogCorrelationContext | undefined, + scope: LogScope | undefined, ): Promise { const [relativePath, root] = splitPath(path, repoPath); @@ -1881,7 +1881,7 @@ export class LocalGitProvider implements GitProvider, Disposable { // Trap and cache expected diff errors if (document.state != null) { const msg = ex?.toString() ?? ''; - Logger.debug(cc, `Cache replace (with empty promise): '${key}'`); + Logger.debug(scope, `Cache replace (with empty promise): '${key}'`); const value: CachedDiff = { item: emptyPromise as Promise, @@ -1898,7 +1898,7 @@ export class LocalGitProvider implements GitProvider, Disposable { @log({ args: { 1: '' } }) async getDiffForFileContents(uri: GitUri, ref: string, contents: string): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const key = `diff:${md5(contents)}`; @@ -1907,12 +1907,12 @@ export class LocalGitProvider implements GitProvider, Disposable { if (doc.state != null) { const cachedDiff = doc.state.getDiff(key); if (cachedDiff != null) { - Logger.debug(cc, `Cache hit: ${key}`); + Logger.debug(scope, `Cache hit: ${key}`); return cachedDiff.item; } } - Logger.debug(cc, `Cache miss: ${key}`); + Logger.debug(scope, `Cache miss: ${key}`); if (doc.state == null) { doc.state = new GitDocumentState(); @@ -1927,11 +1927,11 @@ export class LocalGitProvider implements GitProvider, Disposable { { encoding: GitProviderService.getEncoding(uri) }, doc, key, - cc, + scope, ); if (doc.state != null) { - Logger.debug(cc, `Cache add: '${key}'`); + Logger.debug(scope, `Cache add: '${key}'`); const value: CachedDiff = { item: promise as Promise, @@ -1950,7 +1950,7 @@ export class LocalGitProvider implements GitProvider, Disposable { options: { encoding?: string }, document: TrackedDocument, key: string, - cc: LogCorrelationContext | undefined, + scope: LogScope | undefined, ): Promise { const [relativePath, root] = splitPath(path, repoPath); @@ -1967,7 +1967,7 @@ export class LocalGitProvider implements GitProvider, Disposable { // Trap and cache expected diff errors if (document.state != null) { const msg = ex?.toString() ?? ''; - Logger.debug(cc, `Cache replace (with empty promise): '${key}'`); + Logger.debug(scope, `Cache replace (with empty promise): '${key}'`); const value: CachedDiff = { item: emptyPromise as Promise, @@ -2075,7 +2075,7 @@ export class LocalGitProvider implements GitProvider, Disposable { since?: string; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const limit = options?.limit ?? configuration.get('advanced.maxListItems') ?? 0; @@ -2139,7 +2139,7 @@ export class LocalGitProvider implements GitProvider, Disposable { return log; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; return undefined; } @@ -2158,7 +2158,7 @@ export class LocalGitProvider implements GitProvider, Disposable { since?: string; }, ): Promise | undefined> { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const limit = options?.limit ?? configuration.get('advanced.maxListItems') ?? 0; @@ -2178,7 +2178,7 @@ export class LocalGitProvider implements GitProvider, Disposable { const commits = new Set(parser.parse(data)); return commits; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; return undefined; } @@ -2419,7 +2419,7 @@ export class LocalGitProvider implements GitProvider, Disposable { ): Promise { if (repoPath == null) return undefined; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const relativePath = this.getRelativePath(pathOrUri, repoPath); @@ -2471,7 +2471,7 @@ export class LocalGitProvider implements GitProvider, Disposable { if (doc.state != null) { const cachedLog = doc.state.getLog(key); if (cachedLog != null) { - Logger.debug(cc, `Cache hit: '${key}'`); + Logger.debug(scope, `Cache hit: '${key}'`); return cachedLog.item; } @@ -2482,14 +2482,14 @@ export class LocalGitProvider implements GitProvider, Disposable { ); if (cachedLog != null) { if (options.ref == null) { - Logger.debug(cc, `Cache hit: ~'${key}'`); + Logger.debug(scope, `Cache hit: ~'${key}'`); return cachedLog.item; } - Logger.debug(cc, `Cache ?: '${key}'`); + Logger.debug(scope, `Cache ?: '${key}'`); let log = await cachedLog.item; if (log != null && !log.hasMore && log.commits.has(options.ref)) { - Logger.debug(cc, `Cache hit: '${key}'`); + Logger.debug(scope, `Cache hit: '${key}'`); // Create a copy of the log starting at the requested commit let skip = true; @@ -2529,17 +2529,17 @@ export class LocalGitProvider implements GitProvider, Disposable { } } - Logger.debug(cc, `Cache miss: '${key}'`); + Logger.debug(scope, `Cache miss: '${key}'`); if (doc.state == null) { doc.state = new GitDocumentState(); } } - const promise = this.getLogForFileCore(repoPath, relativePath, options, doc, key, cc); + const promise = this.getLogForFileCore(repoPath, relativePath, options, doc, key, scope); if (doc.state != null && options.range == null) { - Logger.debug(cc, `Cache add: '${key}'`); + Logger.debug(scope, `Cache add: '${key}'`); const value: CachedLog = { item: promise as Promise, @@ -2571,11 +2571,11 @@ export class LocalGitProvider implements GitProvider, Disposable { }, document: TrackedDocument, key: string, - cc: LogCorrelationContext | undefined, + scope: LogScope | undefined, ): Promise { const paths = await this.isTrackedPrivate(path, repoPath, ref); if (paths == null) { - Logger.log(cc, `Skipping blame; '${path}' is not tracked`); + Logger.log(scope, `Skipping blame; '${path}' is not tracked`); return emptyPromise as Promise; } @@ -2621,7 +2621,7 @@ export class LocalGitProvider implements GitProvider, Disposable { // Trap and cache expected log errors if (document.state != null && range == null && !options.reverse) { const msg: string = ex?.toString() ?? ''; - Logger.debug(cc, `Cache replace (with empty promise): '${key}'`); + Logger.debug(scope, `Cache replace (with empty promise): '${key}'`); const value: CachedLog = { item: emptyPromise as Promise, @@ -2699,7 +2699,7 @@ export class LocalGitProvider implements GitProvider, Disposable { @log() async getMergeBase(repoPath: string, ref1: string, ref2: string, options?: { forkPoint?: boolean }) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const data = await this.git.merge_base(repoPath, ref1, ref2, options); @@ -2707,7 +2707,7 @@ export class LocalGitProvider implements GitProvider, Disposable { return data.split('\n')[0].trim() || undefined; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); return undefined; } } @@ -3135,7 +3135,7 @@ export class LocalGitProvider implements GitProvider, Disposable { ): Promise { if (ref === GitRevision.deletedOrMissing) return undefined; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); if (ref === GitRevision.uncommitted) { ref = undefined; @@ -3171,7 +3171,7 @@ export class LocalGitProvider implements GitProvider, Disposable { return GitUri.fromFile(relativePath, repoPath, ref ?? GitRevision.deletedOrMissing); } - Logger.error(ex, cc); + Logger.error(ex, scope); throw ex; } if (data == null || data.length === 0) return undefined; @@ -3188,7 +3188,7 @@ export class LocalGitProvider implements GitProvider, Disposable { repoPath: string, options?: { all?: boolean; branch?: string; limit?: number; ordering?: string | null; skip?: number }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const limit = options?.limit ?? configuration.get('advanced.maxListItems') ?? 0; try { @@ -3207,7 +3207,7 @@ export class LocalGitProvider implements GitProvider, Disposable { return reflog; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); return undefined; } } @@ -3656,12 +3656,12 @@ export class LocalGitProvider implements GitProvider, Disposable { try { let tool = options?.tool; if (!tool) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); tool = configuration.get('advanced.externalDiffTool') || (await this.getDiffTool(root)); if (tool == null) throw new Error('No diff tool found'); - Logger.log(cc, `Using tool=${tool}`); + Logger.log(scope, `Using tool=${tool}`); } await this.git.difftool(root, relativePath, tool, options); @@ -3691,12 +3691,12 @@ export class LocalGitProvider implements GitProvider, Disposable { async openDirectoryCompare(repoPath: string, ref1: string, ref2?: string, tool?: string): Promise { try { if (!tool) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); tool = configuration.get('advanced.externalDirectoryDiffTool') || (await this.getDiffTool(repoPath)); if (tool == null) throw new Error('No diff tool found'); - Logger.log(cc, `Using tool=${tool}`); + Logger.log(scope, `Using tool=${tool}`); } await this.git.difftool__dir_diff(repoPath, tool, ref1, ref2); @@ -3988,31 +3988,31 @@ export class LocalGitProvider implements GitProvider, Disposable { @log() async getOpenScmRepositories(): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const gitApi = await this.getScmGitApi(); return gitApi?.repositories ?? []; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); return []; } } @log() async getScmRepository(repoPath: string): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const gitApi = await this.getScmGitApi(); return gitApi?.getRepository(Uri.file(repoPath)) ?? undefined; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); return undefined; } } @log() async getOrOpenScmRepository(repoPath: string): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const gitApi = await this.getScmGitApi(); if (gitApi?.openRepository != null) { @@ -4021,19 +4021,19 @@ export class LocalGitProvider implements GitProvider, Disposable { return gitApi?.getRepository(Uri.file(repoPath)) ?? undefined; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); return undefined; } } @log() private async openScmRepository(uri: Uri): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const gitApi = await this.getScmGitApi(); return (await gitApi?.openRepository?.(uri)) ?? undefined; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); return undefined; } } diff --git a/src/env/node/git/vslsGitProvider.ts b/src/env/node/git/vslsGitProvider.ts index 5af36e7..71a5be0 100644 --- a/src/env/node/git/vslsGitProvider.ts +++ b/src/env/node/git/vslsGitProvider.ts @@ -5,6 +5,7 @@ import { GitCommandOptions } from '../../../git/commandOptions'; import { GitProviderDescriptor, GitProviderId } from '../../../git/gitProvider'; import { Repository } from '../../../git/models/repository'; import { Logger } from '../../../logger'; +import { getLogScope } from '../../../system/decorators/log'; import { addVslsPrefixIfNeeded } from '../../../system/path'; import { Git } from './git'; import { LocalGitProvider } from './localGitProvider'; @@ -38,7 +39,7 @@ export class VslsGitProvider extends LocalGitProvider { override async discoverRepositories(uri: Uri): Promise { if (!this.supportedSchemes.has(uri.scheme)) return []; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const guest = await this.container.vsls.guest(); @@ -49,7 +50,7 @@ export class VslsGitProvider extends LocalGitProvider { this.openRepository(undefined, Uri.parse(r.folderUri, true), r.root, undefined, r.closed), ); } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; return []; @@ -73,7 +74,7 @@ export class VslsGitProvider extends LocalGitProvider { } override async findRepositoryUri(uri: Uri, isDirectory?: boolean): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); let repoPath: string | undefined; try { @@ -92,7 +93,7 @@ export class VslsGitProvider extends LocalGitProvider { return repoPath ? Uri.parse(repoPath, true) : undefined; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); return undefined; } } diff --git a/src/git/gitProviderService.ts b/src/git/gitProviderService.ts index fd10bcf..b2e39a9 100644 --- a/src/git/gitProviderService.ts +++ b/src/git/gitProviderService.ts @@ -37,7 +37,7 @@ import { } from '../subscription'; import { groupByFilterMap, groupByMap } from '../system/array'; import { gate } from '../system/decorators/gate'; -import { debug, log } from '../system/decorators/log'; +import { debug, getLogScope, log } from '../system/decorators/log'; import { count, filter, first, flatMap, map, some } from '../system/iterable'; import { getBestPath, getScheme, isAbsolute, maybeUri, normalizePath } from '../system/path'; import { cancellable, fastestSettled, isPromise, PromiseCancelledError } from '../system/promise'; @@ -418,7 +418,7 @@ export class GitProviderService implements Disposable { @log({ singleLine: true }) registrationComplete() { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); this._initializing = false; @@ -429,8 +429,8 @@ export class GitProviderService implements Disposable { this.updateContext(); } - if (cc != null) { - cc.exitDetails = ` ${GlyphChars.Dot} workspaceFolders=${ + if (scope != null) { + scope.exitDetails = ` ${GlyphChars.Dot} workspaceFolders=${ workspaceFolders?.length }, git.autoRepositoryDetection=${configuration.getAny( CoreGitConfiguration.AutoRepositoryDetection, @@ -1874,7 +1874,7 @@ export class GitProviderService implements Disposable { @log({ exit: r => `returned ${r?.path}` }) async getOrOpenRepository(uri: Uri, detectNested?: boolean): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const path = getBestPath(uri); let repository: Repository | undefined; @@ -1925,7 +1925,7 @@ export class GitProviderService implements Disposable { const closed = autoRepositoryDetection !== true && autoRepositoryDetection !== 'openEditors'; - Logger.log(cc, `Repository found in '${repoUri.toString(false)}'`); + Logger.log(scope, `Repository found in '${repoUri.toString(false)}'`); const repositories = provider.openRepository(root?.folder, repoUri, false, undefined, closed); for (const repository of repositories) { this._repositories.add(repository); diff --git a/src/git/models/repository.ts b/src/git/models/repository.ts index 8ae04e0..89aa293 100644 --- a/src/git/models/repository.ts +++ b/src/git/models/repository.ts @@ -24,7 +24,7 @@ import { filterMap, groupByMap } from '../../system/array'; import { executeActionCommand, executeCoreGitCommand } from '../../system/command'; import { formatDate, fromNow } from '../../system/date'; import { gate } from '../../system/decorators/gate'; -import { debug, log, logName } from '../../system/decorators/log'; +import { debug, getLogScope, log, logName } from '../../system/decorators/log'; import { debounce } from '../../system/function'; import { filter, join, some } from '../../system/iterable'; import { basename, normalizePath } from '../../system/path'; @@ -1008,7 +1008,7 @@ export class Repository implements Disposable { @debug() private fireChange(...changes: RepositoryChange[]) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); this._updatedAt = Date.now(); @@ -1021,7 +1021,7 @@ export class Repository implements Disposable { this.onDidRepositoryChange(this, new RepositoryChangeEvent(this, changes)); if (this._suspended) { - Logger.debug(cc, `queueing suspended ${this._pendingRepoChange.toString(true)}`); + Logger.debug(scope, `queueing suspended ${this._pendingRepoChange.toString(true)}`); return; } @@ -1041,7 +1041,7 @@ export class Repository implements Disposable { @debug() private fireFileSystemChange(uri: Uri) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); this._updatedAt = Date.now(); @@ -1057,7 +1057,7 @@ export class Repository implements Disposable { e.uris.push(uri); if (this._suspended) { - Logger.debug(cc, `queueing suspended fs changes=${e.uris.map(u => u.fsPath).join(', ')}`); + Logger.debug(scope, `queueing suspended fs changes=${e.uris.map(u => u.fsPath).join(', ')}`); return; } diff --git a/src/git/remotes/provider.ts b/src/git/remotes/provider.ts index f95f07a..296be1b 100644 --- a/src/git/remotes/provider.ts +++ b/src/git/remotes/provider.ts @@ -22,7 +22,7 @@ import { Messages } from '../../messages'; import type { IntegrationAuthenticationSessionDescriptor } from '../../plus/integrationAuthentication'; import { WorkspaceStorageKeys } from '../../storage'; import { gate } from '../../system/decorators/gate'; -import { debug, log } from '../../system/decorators/log'; +import { debug, getLogScope, log } from '../../system/decorators/log'; import { encodeUrl } from '../../system/encoding'; import { isPromise } from '../../system/promise'; import type { Account } from '../models/author'; @@ -451,7 +451,7 @@ export abstract class RichRemoteProvider extends RemoteProvider { avatarSize?: number; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const connected = this.maybeConnected ?? (await this.isConnected()); if (!connected) return undefined; @@ -461,7 +461,7 @@ export abstract class RichRemoteProvider extends RemoteProvider { this.resetRequestExceptionCount(); return author; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) { this.trackRequestException(); @@ -486,7 +486,7 @@ export abstract class RichRemoteProvider extends RemoteProvider { avatarSize?: number; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const connected = this.maybeConnected ?? (await this.isConnected()); if (!connected) return undefined; @@ -496,7 +496,7 @@ export abstract class RichRemoteProvider extends RemoteProvider { this.resetRequestExceptionCount(); return author; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) { this.trackRequestException(); @@ -516,7 +516,7 @@ export abstract class RichRemoteProvider extends RemoteProvider { @gate() @debug() async getDefaultBranch(): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const connected = this.maybeConnected ?? (await this.isConnected()); if (!connected) return undefined; @@ -526,7 +526,7 @@ export abstract class RichRemoteProvider extends RemoteProvider { this.resetRequestExceptionCount(); return defaultBranch; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) { this.trackRequestException(); @@ -542,7 +542,7 @@ export abstract class RichRemoteProvider extends RemoteProvider { @gate() @debug() async getIssueOrPullRequest(id: string): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const connected = this.maybeConnected ?? (await this.isConnected()); if (!connected) return undefined; @@ -552,7 +552,7 @@ export abstract class RichRemoteProvider extends RemoteProvider { this.resetRequestExceptionCount(); return issueOrPullRequest; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) { this.trackRequestException(); @@ -591,7 +591,7 @@ export abstract class RichRemoteProvider extends RemoteProvider { include?: PullRequestState[]; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const connected = this.maybeConnected ?? (await this.isConnected()); if (!connected) return undefined; @@ -601,7 +601,7 @@ export abstract class RichRemoteProvider extends RemoteProvider { this.resetRequestExceptionCount(); return pr; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) { this.trackRequestException(); @@ -634,7 +634,7 @@ export abstract class RichRemoteProvider extends RemoteProvider { @debug() private async getPullRequestForCommitCore(ref: string) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const connected = this.maybeConnected ?? (await this.isConnected()); if (!connected) return null; @@ -645,7 +645,7 @@ export abstract class RichRemoteProvider extends RemoteProvider { this.resetRequestExceptionCount(); return pr; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); this._prsByCommit.delete(ref); diff --git a/src/hovers/hovers.ts b/src/hovers/hovers.ts index e57734a..c9c3257 100644 --- a/src/hovers/hovers.ts +++ b/src/hovers/hovers.ts @@ -12,6 +12,7 @@ import type { PullRequest } from '../git/models/pullRequest'; import { GitRevision } from '../git/models/reference'; import type { GitRemote } from '../git/models/remote'; import { Logger, LogLevel } from '../logger'; +import { getNewLogScope } from '../system/decorators/log'; import { count } from '../system/iterable'; import { PromiseCancelledError } from '../system/promise'; import { getDurationMilliseconds } from '../system/string'; @@ -287,8 +288,8 @@ export namespace Hovers { } async function getAutoLinkedIssuesOrPullRequests(message: string, remotes: GitRemote[]) { - const cc = Logger.getNewCorrelationContext('Hovers.getAutoLinkedIssuesOrPullRequests'); - Logger.debug(cc, `${GlyphChars.Dash} message=`); + const scope = getNewLogScope('Hovers.getAutoLinkedIssuesOrPullRequests'); + Logger.debug(scope, `${GlyphChars.Dash} message=`); const start = hrtime(); @@ -298,14 +299,14 @@ export namespace Hovers { !cfg.autolinks.enhanced || !CommitFormatter.has(cfg.detailsMarkdownFormat, 'message') ) { - Logger.debug(cc, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); + Logger.debug(scope, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); return undefined; } const remote = await Container.instance.git.getBestRemoteWithRichProvider(remotes); if (remote?.provider == null) { - Logger.debug(cc, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); + Logger.debug(scope, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); return undefined; } @@ -323,7 +324,7 @@ export namespace Hovers { const prCount = count(autolinks.values(), pr => pr instanceof PromiseCancelledError); if (prCount !== 0) { Logger.debug( - cc, + scope, `timed out ${ GlyphChars.Dash } ${prCount} issue/pull request queries took too long (over ${timeout} ms) ${ @@ -340,7 +341,7 @@ export namespace Hovers { // ]; // void Promise.all(pending).then(() => { // Logger.debug( - // cc, + // scope, // `${GlyphChars.Dot} ${count} issue/pull request queries completed; refreshing...`, // ); // void executeCoreCommand(CoreCommands.EditorShowHover); @@ -350,11 +351,11 @@ export namespace Hovers { } } - Logger.debug(cc, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); + Logger.debug(scope, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); return autolinks; } catch (ex) { - Logger.error(ex, cc, `failed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); + Logger.error(ex, scope, `failed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); return undefined; } @@ -367,13 +368,13 @@ export namespace Hovers { pullRequests?: boolean; }, ) { - const cc = Logger.getNewCorrelationContext('Hovers.getPullRequestForCommit'); - Logger.debug(cc, `${GlyphChars.Dash} ref=${ref}`); + const scope = getNewLogScope('Hovers.getPullRequestForCommit'); + Logger.debug(scope, `${GlyphChars.Dash} ref=${ref}`); const start = hrtime(); if (!options?.pullRequests) { - Logger.debug(cc, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); + Logger.debug(scope, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); return undefined; } @@ -382,7 +383,7 @@ export namespace Hovers { includeDisconnected: true, }); if (remote?.provider == null) { - Logger.debug(cc, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); + Logger.debug(scope, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); return undefined; } @@ -390,7 +391,7 @@ export namespace Hovers { const { provider } = remote; const connected = provider.maybeConnected ?? (await provider.isConnected()); if (!connected) { - Logger.debug(cc, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); + Logger.debug(scope, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); return remote; } @@ -398,17 +399,17 @@ export namespace Hovers { try { const pr = await Container.instance.git.getPullRequestForCommit(ref, provider, { timeout: 250 }); - Logger.debug(cc, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); + Logger.debug(scope, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); return pr; } catch (ex) { if (ex instanceof PromiseCancelledError) { - Logger.debug(cc, `timed out ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); + Logger.debug(scope, `timed out ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); return ex; } - Logger.error(ex, cc, `failed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); + Logger.error(ex, scope, `failed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`); return undefined; } diff --git a/src/keyboard.ts b/src/keyboard.ts index 20fe04f..b7c79d8 100644 --- a/src/keyboard.ts +++ b/src/keyboard.ts @@ -2,7 +2,7 @@ import { commands, Disposable } from 'vscode'; import { ContextKeys } from './constants'; import { setContext } from './context'; import { Logger } from './logger'; -import { log } from './system/decorators/log'; +import { getLogScope, log } from './system/decorators/log'; export declare interface KeyCommand { onDidPressKey?(key: Keys): void | Promise; @@ -49,9 +49,9 @@ export class KeyboardScope implements Disposable { async dispose() { const index = mappings.indexOf(this._mapping); - const cc = Logger.getCorrelationContext(); - if (cc != null) { - cc.exitDetails = ` \u2022 index=${index}`; + const scope = getLogScope(); + if (scope != null) { + scope.exitDetails = ` \u2022 index=${index}`; } if (index === mappings.length - 1) { @@ -72,12 +72,12 @@ export class KeyboardScope implements Disposable { prefix: (context, key) => `${context.prefix}[${mappings.length}](${key})`, }) async clearKeyCommand(key: Keys) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const mapping = mappings[mappings.length - 1]; if (mapping !== this._mapping || mapping[key] == null) { - if (cc != null) { - cc.exitDetails = ' \u2022 skipped'; + if (scope != null) { + scope.exitDetails = ' \u2022 skipped'; } return; @@ -123,12 +123,12 @@ export class KeyboardScope implements Disposable { prefix: (context, key) => `${context.prefix}[${mappings.length}](${key})`, }) async setKeyCommand(key: Keys, command: KeyCommand | (() => Promise)) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const mapping = mappings[mappings.length - 1]; if (mapping !== this._mapping) { - if (cc != null) { - cc.exitDetails = ' \u2022 skipped'; + if (scope != null) { + scope.exitDetails = ' \u2022 skipped'; } return; @@ -183,11 +183,11 @@ export class Keyboard implements Disposable { @log() async execute(key: Keys): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); if (!mappings.length) { - if (cc != null) { - cc.exitDetails = ' \u2022 skipped, no mappings'; + if (scope != null) { + scope.exitDetails = ' \u2022 skipped, no mappings'; } return; @@ -201,8 +201,8 @@ export class Keyboard implements Disposable { command = await command(); } if (typeof command?.onDidPressKey !== 'function') { - if (cc != null) { - cc.exitDetails = ' \u2022 skipped, no callback'; + if (scope != null) { + scope.exitDetails = ' \u2022 skipped, no callback'; } return; @@ -210,7 +210,7 @@ export class Keyboard implements Disposable { void (await command.onDidPressKey(key)); } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); } } } diff --git a/src/logger.ts b/src/logger.ts index e87b96b..4481fd5 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -1,6 +1,5 @@ import { ExtensionContext, ExtensionMode, OutputChannel, Uri, window } from 'vscode'; import { OutputLevel } from './configuration'; -import { getCorrelationContext, getNextCorrelationId } from './system/decorators/log'; const emptyStr = ''; const outputChannelName = 'GitLens'; @@ -17,6 +16,12 @@ export const enum LogLevel { Debug = 'debug', } +export interface LogScope { + readonly scopeId?: number; + readonly prefix: string; + exitDetails?: string; +} + const enum OrderedLevel { Off = 0, Error = 1, @@ -25,12 +30,6 @@ const enum OrderedLevel { Debug = 4, } -export interface LogCorrelationContext { - readonly correlationId?: number; - readonly prefix: string; - exitDetails?: string; -} - export class Logger { static readonly slowCallWarningThreshold = 500; @@ -70,18 +69,18 @@ export class Logger { } static debug(message: string, ...params: any[]): void; - static debug(context: LogCorrelationContext | undefined, message: string, ...params: any[]): void; - static debug(contextOrMessage: LogCorrelationContext | string | undefined, ...params: any[]): void { + static debug(scope: LogScope | undefined, message: string, ...params: any[]): void; + static debug(scopeOrMessage: LogScope | string | undefined, ...params: any[]): void { if (this.level < OrderedLevel.Debug && !this.isDebugging) return; let message; - if (typeof contextOrMessage === 'string') { - message = contextOrMessage; + if (typeof scopeOrMessage === 'string') { + message = scopeOrMessage; } else { message = params.shift(); - if (contextOrMessage != null) { - message = `${contextOrMessage.prefix} ${message ?? emptyStr}`; + if (scopeOrMessage != null) { + message = `${scopeOrMessage.prefix} ${message ?? emptyStr}`; } } @@ -94,19 +93,15 @@ export class Logger { } static error(ex: Error | unknown, message?: string, ...params: any[]): void; - static error(ex: Error | unknown, context?: LogCorrelationContext, message?: string, ...params: any[]): void; - static error( - ex: Error | unknown, - contextOrMessage: LogCorrelationContext | string | undefined, - ...params: any[] - ): void { + static error(ex: Error | unknown, scope?: LogScope, message?: string, ...params: any[]): void; + static error(ex: Error | unknown, scopeOrMessage: LogScope | string | undefined, ...params: any[]): void { if (this.level < OrderedLevel.Error && !this.isDebugging) return; let message; - if (contextOrMessage == null || typeof contextOrMessage === 'string') { - message = contextOrMessage; + if (scopeOrMessage == null || typeof scopeOrMessage === 'string') { + message = scopeOrMessage; } else { - message = `${contextOrMessage.prefix} ${params.shift() ?? emptyStr}`; + message = `${scopeOrMessage.prefix} ${params.shift() ?? emptyStr}`; } if (message == null) { @@ -130,18 +125,18 @@ export class Logger { } static log(message: string, ...params: any[]): void; - static log(context: LogCorrelationContext | undefined, message: string, ...params: any[]): void; - static log(contextOrMessage: LogCorrelationContext | string | undefined, ...params: any[]): void { + static log(scope: LogScope | undefined, message: string, ...params: any[]): void; + static log(scopeOrMessage: LogScope | string | undefined, ...params: any[]): void { if (this.level < OrderedLevel.Info && !this.isDebugging) return; let message; - if (typeof contextOrMessage === 'string') { - message = contextOrMessage; + if (typeof scopeOrMessage === 'string') { + message = scopeOrMessage; } else { message = params.shift(); - if (contextOrMessage != null) { - message = `${contextOrMessage.prefix} ${message ?? emptyStr}`; + if (scopeOrMessage != null) { + message = `${scopeOrMessage.prefix} ${message ?? emptyStr}`; } } @@ -154,18 +149,18 @@ export class Logger { } static warn(message: string, ...params: any[]): void; - static warn(context: LogCorrelationContext | undefined, message: string, ...params: any[]): void; - static warn(contextOrMessage: LogCorrelationContext | string | undefined, ...params: any[]): void { + static warn(scope: LogScope | undefined, message: string, ...params: any[]): void; + static warn(scopeOrMessage: LogScope | string | undefined, ...params: any[]): void { if (this.level < OrderedLevel.Warn && !this.isDebugging) return; let message; - if (typeof contextOrMessage === 'string') { - message = contextOrMessage; + if (typeof scopeOrMessage === 'string') { + message = scopeOrMessage; } else { message = params.shift(); - if (contextOrMessage != null) { - message = `${contextOrMessage.prefix} ${message ?? emptyStr}`; + if (scopeOrMessage != null) { + message = `${scopeOrMessage.prefix} ${message ?? emptyStr}`; } } @@ -177,18 +172,6 @@ export class Logger { this.output.appendLine(`${this.timestamp} ${message ?? emptyStr}${this.toLoggableParams(false, params)}`); } - static getCorrelationContext() { - return getCorrelationContext(); - } - - static getNewCorrelationContext(prefix: string): LogCorrelationContext { - const correlationId = getNextCorrelationId(); - return { - correlationId: correlationId, - prefix: `[${String(correlationId).padStart(5)}] ${prefix}`, - }; - } - static showOutputChannel(): void { this.output?.show(); } diff --git a/src/plus/github/github.ts b/src/plus/github/github.ts index 1282e8a..32daf98 100644 --- a/src/plus/github/github.ts +++ b/src/plus/github/github.ts @@ -24,9 +24,9 @@ import { GitRevision } from '../../git/models/reference'; import type { GitUser } from '../../git/models/user'; import { getGitHubNoReplyAddressParts } from '../../git/remotes/github'; import type { RichRemoteProvider } from '../../git/remotes/provider'; -import { LogCorrelationContext, Logger, LogLevel } from '../../logger'; +import { Logger, LogLevel, LogScope } from '../../logger'; import { Messages } from '../../messages'; -import { debug } from '../../system/decorators/log'; +import { debug, getLogScope } from '../../system/decorators/log'; import { Stopwatch } from '../../system/stopwatch'; import { base64 } from '../../system/string'; import { fromString, satisfies, Version } from '../../system/version'; @@ -103,7 +103,7 @@ export class GitHubApi implements Disposable { avatarSize?: number; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { repository: @@ -153,7 +153,7 @@ export class GitHubApi implements Disposable { repo: repo, ref: ref, }, - cc, + scope, ); const author = rsp?.repository?.object?.author; @@ -180,7 +180,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, provider, cc); + throw this.handleException(ex, provider, scope); } } @@ -196,7 +196,7 @@ export class GitHubApi implements Disposable { avatarSize?: number; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { search: @@ -240,7 +240,7 @@ export class GitHubApi implements Disposable { repo: repo, emailQuery: `in:email ${email}`, }, - cc, + scope, ); const author = rsp?.search?.nodes?.[0]; @@ -267,7 +267,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, provider, cc); + throw this.handleException(ex, provider, scope); } } @@ -281,7 +281,7 @@ export class GitHubApi implements Disposable { baseUrl?: string; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { repository: @@ -313,7 +313,7 @@ export class GitHubApi implements Disposable { owner: owner, repo: repo, }, - cc, + scope, ); const defaultBranch = rsp?.repository?.defaultBranchRef?.name ?? undefined; @@ -326,7 +326,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, provider, cc); + throw this.handleException(ex, provider, scope); } } @@ -341,7 +341,7 @@ export class GitHubApi implements Disposable { baseUrl?: string; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { repository?: { issueOrPullRequest?: GitHubIssueOrPullRequest }; @@ -384,7 +384,7 @@ export class GitHubApi implements Disposable { repo: repo, number: number, }, - cc, + scope, ); const issue = rsp?.repository?.issueOrPullRequest; @@ -403,7 +403,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, provider, cc); + throw this.handleException(ex, provider, scope); } } @@ -420,7 +420,7 @@ export class GitHubApi implements Disposable { include?: GitHubPullRequestState[]; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { repository: @@ -488,7 +488,7 @@ export class GitHubApi implements Disposable { // Since GitHub sort doesn't seem to really work, look for a max of 10 PRs and then sort them ourselves limit: 10, }, - cc, + scope, ); // If the pr is not from a fork, keep it e.g. show root pr's on forks, otherwise, ensure the repo owners match @@ -510,7 +510,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, provider, cc); + throw this.handleException(ex, provider, scope); } } @@ -526,7 +526,7 @@ export class GitHubApi implements Disposable { avatarSize?: number; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { repository: @@ -588,7 +588,7 @@ export class GitHubApi implements Disposable { repo: repo, ref: ref, }, - cc, + scope, ); // If the pr is not from a fork, keep it e.g. show root pr's on forks, otherwise, ensure the repo owners match @@ -610,13 +610,13 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, provider, cc); + throw this.handleException(ex, provider, scope); } } @debug({ args: { 0: '' } }) async getBlame(token: string, owner: string, repo: string, ref: string, path: string): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { viewer: { name: string }; @@ -682,7 +682,7 @@ export class GitHubApi implements Disposable { ref: ref, path: path, }, - cc, + scope, ); if (rsp == null) return emptyBlameResult; @@ -693,7 +693,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return emptyBlameResult; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } } @@ -704,7 +704,7 @@ export class GitHubApi implements Disposable { repo: string, options?: { query?: string; cursor?: string; limit?: number }, ): Promise> { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { repository: @@ -761,7 +761,7 @@ export class GitHubApi implements Disposable { cursor: options?.cursor, limit: Math.min(100, options?.limit ?? 100), }, - cc, + scope, ); if (rsp == null) return emptyPagedResult; @@ -778,7 +778,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return emptyPagedResult; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } } @@ -789,7 +789,7 @@ export class GitHubApi implements Disposable { repo: string, ref: string, ): Promise<(GitHubCommit & { viewer?: string }) | undefined> { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const rsp = await this.request( @@ -801,7 +801,7 @@ export class GitHubApi implements Disposable { repo: repo, ref: ref, }, - cc, + scope, ); const result = rsp?.data; @@ -831,7 +831,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } // const results = await this.getCommits(token, owner, repo, ref, { limit: 1 }); @@ -860,7 +860,7 @@ export class GitHubApi implements Disposable { @debug({ args: { 0: '' } }) async getCommitBranches(token: string, owner: string, repo: string, ref: string, date: Date): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { repository: { @@ -909,7 +909,7 @@ export class GitHubApi implements Disposable { since: date.toISOString(), until: date.toISOString(), }, - cc, + scope, ); const nodes = rsp?.repository?.refs?.nodes; @@ -930,13 +930,13 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return []; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } } @debug({ args: { 0: '' } }) async getCommitCount(token: string, owner: string, repo: string, ref: string): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { repository: { @@ -976,7 +976,7 @@ export class GitHubApi implements Disposable { repo: repo, ref: ref, }, - cc, + scope, ); const count = rsp?.repository?.ref?.target.history.totalCount; @@ -984,7 +984,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } } @@ -997,7 +997,7 @@ export class GitHubApi implements Disposable { ref: string, date: Date, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { repository: { @@ -1041,7 +1041,7 @@ export class GitHubApi implements Disposable { since: date.toISOString(), until: date.toISOString(), }, - cc, + scope, ); const nodes = rsp?.repository?.ref.target.history.nodes; @@ -1060,7 +1060,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return []; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } } @@ -1081,7 +1081,7 @@ export class GitHubApi implements Disposable { until?: string | Date; }, ): Promise & { viewer?: string }> { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); if (options?.limit === 1 && options?.path == null) { return this.getCommitsCoreSingle(token, owner, repo, ref); @@ -1186,7 +1186,7 @@ export class GitHubApi implements Disposable { since: typeof options?.since === 'string' ? options?.since : options?.since?.toISOString(), until: typeof options?.until === 'string' ? options?.until : options?.until?.toISOString(), }, - cc, + scope, ); const history = rsp?.repository?.object?.history; if (history == null) return emptyPagedResult; @@ -1205,7 +1205,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return emptyPagedResult; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } } @@ -1215,7 +1215,7 @@ export class GitHubApi implements Disposable { repo: string, ref: string, ): Promise & { viewer?: string }> { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { viewer: { name: string }; @@ -1263,7 +1263,7 @@ export class GitHubApi implements Disposable { repo: repo, ref: ref, }, - cc, + scope, ); if (rsp == null) return emptyPagedResult; @@ -1272,7 +1272,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return emptyPagedResult; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } } @@ -1292,7 +1292,7 @@ export class GitHubApi implements Disposable { until?: string; }, ): Promise | undefined> { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { repository: @@ -1354,7 +1354,7 @@ export class GitHubApi implements Disposable { since: options?.since, until: options?.until, }, - cc, + scope, ); const history = rsp?.repository?.object?.history; if (history == null) return undefined; @@ -1367,7 +1367,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } } @@ -1412,7 +1412,7 @@ export class GitHubApi implements Disposable { } private async getCommitDate(token: string, owner: string, repo: string, sha: string): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { repository: @@ -1445,20 +1445,20 @@ export class GitHubApi implements Disposable { repo: repo, sha: sha, }, - cc, + scope, ); const date = rsp?.repository?.object?.committer.date; return date; } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } } @debug({ args: { 0: '' } }) async getContributors(token: string, owner: string, repo: string): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); // TODO@eamodio implement pagination @@ -1472,7 +1472,7 @@ export class GitHubApi implements Disposable { repo: repo, per_page: 100, }, - cc, + scope, ); const result = rsp?.data; @@ -1482,13 +1482,13 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return []; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } } @debug({ args: { 0: '' } }) async getDefaultBranchName(token: string, owner: string, repo: string): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { repository: @@ -1519,7 +1519,7 @@ export class GitHubApi implements Disposable { owner: owner, repo: repo, }, - cc, + scope, ); if (rsp == null) return undefined; @@ -1527,13 +1527,13 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } } @debug({ args: { 0: '' } }) async getCurrentUser(token: string, owner: string, repo: string): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { viewer: { @@ -1562,7 +1562,7 @@ export class GitHubApi implements Disposable { owner: owner, repo: repo, }, - cc, + scope, ); if (rsp == null) return undefined; @@ -1575,7 +1575,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } } @@ -1585,7 +1585,7 @@ export class GitHubApi implements Disposable { owner: string, repo: string, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { repository: @@ -1614,7 +1614,7 @@ export class GitHubApi implements Disposable { owner: owner, repo: repo, }, - cc, + scope, ); if (rsp?.repository?.visibility == null) return undefined; @@ -1622,7 +1622,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } } @@ -1633,7 +1633,7 @@ export class GitHubApi implements Disposable { repo: string, options?: { query?: string; cursor?: string; limit?: number }, ): Promise> { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { repository: @@ -1695,7 +1695,7 @@ export class GitHubApi implements Disposable { cursor: options?.cursor, limit: Math.min(100, options?.limit ?? 100), }, - cc, + scope, ); if (rsp == null) return emptyPagedResult; @@ -1712,7 +1712,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return emptyPagedResult; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } } @@ -1724,7 +1724,7 @@ export class GitHubApi implements Disposable { ref: string, path?: string, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { if (!path) { @@ -1753,7 +1753,7 @@ export class GitHubApi implements Disposable { repo: repo, ref: ref, }, - cc, + scope, ); return rsp?.repository?.object?.oid ?? undefined; } @@ -1798,13 +1798,13 @@ export class GitHubApi implements Disposable { ref: ref, path: path, }, - cc, + scope, ); return rsp?.repository?.object?.history.nodes?.[0]?.oid ?? undefined; } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } } @@ -1819,7 +1819,7 @@ export class GitHubApi implements Disposable { sort?: 'author-date' | 'committer-date' | undefined; }, ): Promise | undefined> { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const limit = Math.min(100, options?.limit ?? 100); @@ -1850,7 +1850,7 @@ export class GitHubApi implements Disposable { per_page: pageSize, page: page, }, - cc, + scope, ); const data = rsp?.data; @@ -1889,7 +1889,7 @@ export class GitHubApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, undefined, cc); + throw this.handleException(ex, undefined, scope); } } @@ -1905,10 +1905,10 @@ export class GitHubApi implements Disposable { if (version != null) return version; if (version === null) return undefined; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { - const rsp = await this.request(provider, token, 'GET /meta', options, cc); + const rsp = await this.request(provider, token, 'GET /meta', options, scope); const v = (rsp?.data as any)?.installed_version as string | null | undefined; version = v ? fromString(v) : null; } catch (ex) { @@ -1975,7 +1975,7 @@ export class GitHubApi implements Disposable { token: string, query: string, variables: { [key: string]: any }, - cc: LogCorrelationContext | undefined, + scope: LogScope | undefined, ): Promise { try { return await wrapForForcedInsecureSSL(provider?.getIgnoreSSLErrors() ?? false, () => @@ -2007,7 +2007,7 @@ export class GitHubApi implements Disposable { void window.showErrorMessage(`GitHub request failed: ${ex.errors?.[0]?.message ?? ex.message}`); } } else if (ex instanceof RequestError) { - this.handleRequestError(provider, token, ex, cc); + this.handleRequestError(provider, token, ex, scope); } else if (Logger.isDebugging) { void window.showErrorMessage(`GitHub request failed: ${ex.message}`); } @@ -2023,7 +2023,7 @@ export class GitHubApi implements Disposable { options: | (R extends keyof Endpoints ? Endpoints[R]['parameters'] & RequestParameters : RequestParameters) | undefined, - cc: LogCorrelationContext | undefined, + scope: LogScope | undefined, ): Promise> { try { return (await wrapForForcedInsecureSSL(provider?.getIgnoreSSLErrors() ?? false, () => @@ -2031,7 +2031,7 @@ export class GitHubApi implements Disposable { )) as any; } catch (ex) { if (ex instanceof RequestError) { - this.handleRequestError(provider, token, ex, cc); + this.handleRequestError(provider, token, ex, scope); } else if (Logger.isDebugging) { void window.showErrorMessage(`GitHub request failed: ${ex.message}`); } @@ -2044,7 +2044,7 @@ export class GitHubApi implements Disposable { provider: RichRemoteProvider | undefined, token: string, ex: RequestError, - cc: LogCorrelationContext | undefined, + scope: LogScope | undefined, ): void { switch (ex.status) { case 404: // Not found @@ -2070,7 +2070,7 @@ export class GitHubApi implements Disposable { } throw new AuthenticationError('github', AuthenticationErrorReason.Forbidden, ex); case 500: // Internal Server Error - Logger.error(ex, cc); + Logger.error(ex, scope); if (ex.response != null) { provider?.trackRequestException(); void Messages.showIntegrationRequestFailed500WarningMessage( @@ -2083,7 +2083,7 @@ export class GitHubApi implements Disposable { } return; case 502: // Bad Gateway - Logger.error(ex, cc); + Logger.error(ex, scope); // GitHub seems to return this status code for timeouts if (ex.message.includes('timeout')) { provider?.trackRequestException(); @@ -2096,7 +2096,7 @@ export class GitHubApi implements Disposable { break; } - Logger.error(ex, cc); + Logger.error(ex, scope); if (Logger.isDebugging) { void window.showErrorMessage( `GitHub request failed: ${(ex.response as any)?.errors?.[0]?.message ?? ex.message}`, @@ -2104,12 +2104,8 @@ export class GitHubApi implements Disposable { } } - private handleException( - ex: Error, - provider: RichRemoteProvider | undefined, - cc: LogCorrelationContext | undefined, - ): Error { - Logger.error(ex, cc); + private handleException(ex: Error, provider: RichRemoteProvider | undefined, scope: LogScope | undefined): Error { + Logger.error(ex, scope); // debugger; if (ex instanceof AuthenticationError) { diff --git a/src/plus/github/githubGitProvider.ts b/src/plus/github/githubGitProvider.ts index 8c8191e..c8957e1 100644 --- a/src/plus/github/githubGitProvider.ts +++ b/src/plus/github/githubGitProvider.ts @@ -60,9 +60,9 @@ import { GitUser, isUserMatch } from '../../git/models/user'; import { RemoteProviderFactory, RemoteProviders } from '../../git/remotes/factory'; import type { RemoteProvider, RichRemoteProvider } from '../../git/remotes/provider'; import { SearchPattern } from '../../git/search'; -import { LogCorrelationContext, Logger } from '../../logger'; +import { Logger, LogScope } from '../../logger'; import { gate } from '../../system/decorators/gate'; -import { debug, log } from '../../system/decorators/log'; +import { debug, getLogScope, log } from '../../system/decorators/log'; import { filterMap, some } from '../../system/iterable'; import { isAbsolute, isFolderGlob, maybeUri, normalizePath, relative } from '../../system/path'; import { getSettledValue } from '../../system/promise'; @@ -364,7 +364,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { @gate() @debug() async findRepositoryUri(uri: Uri, _isDirectory?: boolean): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const remotehub = await this.ensureRemoteHubApi(); @@ -374,7 +374,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { if (!(ex instanceof ExtensionNotFoundError)) { debugger; } - Logger.error(ex, cc); + Logger.error(ex, scope); return undefined; } @@ -391,7 +391,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { @gate((u, d) => `${u.toString()}|${d?.isDirty}`) @log({ args: { 1: d => d?.isDirty } }) async getBlame(uri: GitUri, document?: TextDocument | undefined): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); // TODO@eamodio we need to figure out when to do this, since dirty isn't enough, we need to know if there are any uncommitted changes if (document?.isDirty) return undefined; //this.getBlameContents(uri, document.getText()); @@ -405,21 +405,21 @@ export class GitHubGitProvider implements GitProvider, Disposable { if (doc.state != null) { const cachedBlame = doc.state.getBlame(key); if (cachedBlame != null) { - Logger.debug(cc, `Cache hit: '${key}'`); + Logger.debug(scope, `Cache hit: '${key}'`); return cachedBlame.item; } } - Logger.debug(cc, `Cache miss: '${key}'`); + Logger.debug(scope, `Cache miss: '${key}'`); if (doc.state == null) { doc.state = new GitDocumentState(); } - const promise = this.getBlameCore(uri, doc, key, cc); + const promise = this.getBlameCore(uri, doc, key, scope); if (doc.state != null) { - Logger.debug(cc, `Cache add: '${key}'`); + Logger.debug(scope, `Cache add: '${key}'`); const value: CachedBlame = { item: promise as Promise, @@ -434,7 +434,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { uri: GitUri, document: TrackedDocument, key: string, - cc: LogCorrelationContext | undefined, + scope: LogScope | undefined, ): Promise { try { const context = await this.ensureRepositoryContext(uri.repoPath!); @@ -530,7 +530,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { // Trap and cache expected blame errors if (document.state != null && !/No provider registered with/.test(String(ex))) { const msg = ex?.toString() ?? ''; - Logger.debug(cc, `Cache replace (with empty promise): '${key}'`); + Logger.debug(scope, `Cache replace (with empty promise): '${key}'`); const value: CachedBlame = { item: emptyPromise as Promise, @@ -563,7 +563,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { document?: TextDocument | undefined, options?: { forceSingleLine?: boolean }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); // TODO@eamodio we need to figure out when to do this, since dirty isn't enough, we need to know if there are any uncommitted changes if (document?.isDirty) return undefined; //this.getBlameForLineContents(uri, editorLine, document.getText(), options); @@ -648,7 +648,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { }; } catch (ex) { debugger; - Logger.error(cc, ex); + Logger.error(scope, ex); return undefined; } } @@ -747,7 +747,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { ): Promise> { if (repoPath == null) return emptyPagedResult; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); let branchesPromise = options?.cursor ? undefined : this._branchesCache.get(repoPath); if (branchesPromise == null) { @@ -793,7 +793,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { cursor = result.paging.cursor; } } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; this._branchesCache.delete(repoPath!); @@ -843,7 +843,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { async getCommit(repoPath: string, ref: string): Promise { if (repoPath == null) return undefined; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const { metadata, github, session } = await this.ensureRepositoryContext(repoPath); @@ -888,7 +888,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { [], ); } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; return undefined; } @@ -902,7 +902,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { ): Promise { if (repoPath == null || options?.commitDate == null) return []; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const { metadata, github, session } = await this.ensureRepositoryContext(repoPath); @@ -930,7 +930,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { return branches; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; return []; } @@ -940,7 +940,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { async getCommitCount(repoPath: string, ref: string): Promise { if (repoPath == null) return undefined; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const { metadata, github, session } = await this.ensureRepositoryContext(repoPath); @@ -954,7 +954,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { return count; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; return undefined; } @@ -968,7 +968,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { ): Promise { if (repoPath == null) return undefined; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const { metadata, github, remotehub, session } = await this.ensureRepositoryContext(repoPath); @@ -1025,7 +1025,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { [], ); } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; return undefined; } @@ -1044,7 +1044,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { ): Promise { if (repoPath == null) return []; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const { metadata, github, session } = await this.ensureRepositoryContext(repoPath); @@ -1074,7 +1074,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { return contributors; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; return []; } @@ -1085,7 +1085,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { async getCurrentUser(repoPath: string): Promise { if (!repoPath) return undefined; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const repo = this._repoInfoCache.get(repoPath); @@ -1101,7 +1101,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { this._repoInfoCache.set(repoPath, { ...repo, user: user ?? null }); return user; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; // Mark it so we won't bother trying again @@ -1114,13 +1114,13 @@ export class GitHubGitProvider implements GitProvider, Disposable { async getDefaultBranchName(repoPath: string | undefined, _remote?: string): Promise { if (repoPath == null) return undefined; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const { metadata, github, session } = await this.ensureRepositoryContext(repoPath); return await github.getDefaultBranchName(session.accessToken, metadata.repo.owner, metadata.repo.name); } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; return undefined; } @@ -1190,7 +1190,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { ): Promise { if (repoPath == null) return undefined; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const limit = this.getPagingLimit(options?.limit); @@ -1274,7 +1274,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { return log; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; return undefined; } @@ -1376,7 +1376,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { ): Promise { if (repoPath == null) return undefined; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const operations = SearchPattern.parseSearchOperations(search.pattern); @@ -1514,7 +1514,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { return log; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; return undefined; } @@ -1577,7 +1577,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { ): Promise { if (repoPath == null) return undefined; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const relativePath = this.getRelativePath(pathOrUri, repoPath); @@ -1637,7 +1637,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { if (doc.state != null) { const cachedLog = doc.state.getLog(key); if (cachedLog != null) { - Logger.debug(cc, `Cache hit: '${key}'`); + Logger.debug(scope, `Cache hit: '${key}'`); return cachedLog.item; } @@ -1648,14 +1648,14 @@ export class GitHubGitProvider implements GitProvider, Disposable { ); if (cachedLog != null) { if (options.ref == null) { - Logger.debug(cc, `Cache hit: ~'${key}'`); + Logger.debug(scope, `Cache hit: ~'${key}'`); return cachedLog.item; } - Logger.debug(cc, `Cache ?: '${key}'`); + Logger.debug(scope, `Cache ?: '${key}'`); let log = await cachedLog.item; if (log != null && !log.hasMore && log.commits.has(options.ref)) { - Logger.debug(cc, `Cache hit: '${key}'`); + Logger.debug(scope, `Cache hit: '${key}'`); // Create a copy of the log starting at the requested commit let skip = true; @@ -1695,17 +1695,17 @@ export class GitHubGitProvider implements GitProvider, Disposable { } } - Logger.debug(cc, `Cache miss: '${key}'`); + Logger.debug(scope, `Cache miss: '${key}'`); if (doc.state == null) { doc.state = new GitDocumentState(); } } - const promise = this.getLogForFileCore(repoPath, relativePath, doc, key, cc, options); + const promise = this.getLogForFileCore(repoPath, relativePath, doc, key, scope, options); if (doc.state != null && options.range == null) { - Logger.debug(cc, `Cache add: '${key}'`); + Logger.debug(scope, `Cache add: '${key}'`); const value: CachedLog = { item: promise as Promise, @@ -1721,7 +1721,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { path: string, document: TrackedDocument, key: string, - cc: LogCorrelationContext | undefined, + scope: LogScope | undefined, options?: { all?: boolean; cursor?: string; @@ -1843,7 +1843,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { // Trap and cache expected log errors if (document.state != null && options?.range == null && !options?.reverse) { const msg: string = ex?.toString() ?? ''; - Logger.debug(cc, `Cache replace (with empty promise): '${key}'`); + Logger.debug(scope, `Cache replace (with empty promise): '${key}'`); const value: CachedLog = { item: emptyPromise as Promise, @@ -1952,7 +1952,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { // If we have no ref there is no next commit if (!ref) return undefined; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const context = await this.ensureRepositoryContext(repoPath); @@ -1983,7 +1983,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { next: new GitUri(await this.getBestRevisionUri(repoPath, relativePath, refs[skip])), }; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; throw ex; @@ -2000,7 +2000,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { ): Promise { if (ref === GitRevision.deletedOrMissing) return undefined; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); if (ref === GitRevision.uncommitted) { ref = undefined; @@ -2051,7 +2051,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { ), }; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; throw ex; @@ -2068,7 +2068,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { ): Promise { if (ref === GitRevision.deletedOrMissing) return undefined; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const context = await this.ensureRepositoryContext(repoPath); @@ -2117,7 +2117,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { line: (currentLine ?? editorLine) + 1, // 1-based }; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; throw ex; @@ -2199,7 +2199,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { ): Promise> { if (repoPath == null) return emptyPagedResult; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); let tagsPromise = options?.cursor ? undefined : this._tagsCache.get(repoPath); if (tagsPromise == null) { @@ -2238,7 +2238,7 @@ export class GitHubGitProvider implements GitProvider, Disposable { cursor = result.paging.cursor; } } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; this._tagsCache.delete(repoPath!); diff --git a/src/plus/gitlab/gitlab.ts b/src/plus/gitlab/gitlab.ts index 2db53be..7ba6332 100644 --- a/src/plus/gitlab/gitlab.ts +++ b/src/plus/gitlab/gitlab.ts @@ -18,9 +18,9 @@ import type { DefaultBranch } from '../../git/models/defaultBranch'; import { IssueOrPullRequest, IssueOrPullRequestType } from '../../git/models/issue'; import { PullRequest } from '../../git/models/pullRequest'; import type { RichRemoteProvider } from '../../git/remotes/provider'; -import { LogCorrelationContext, Logger, LogLevel } from '../../logger'; +import { Logger, LogLevel, LogScope } from '../../logger'; import { Messages } from '../../messages'; -import { debug } from '../../system/decorators/log'; +import { debug, getLogScope } from '../../system/decorators/log'; import { Stopwatch } from '../../system/stopwatch'; import { equalsIgnoreCase } from '../../system/string'; import { @@ -83,7 +83,7 @@ export class GitLabApi implements Disposable { avatarSize?: number; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const projectId = await this.getProjectId(provider, token, owner, repo, options?.baseUrl); if (!projectId) return undefined; @@ -98,7 +98,7 @@ export class GitLabApi implements Disposable { method: 'GET', // ...options, }, - cc, + scope, ); let user: GitLabUser | undefined; @@ -132,7 +132,7 @@ export class GitLabApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, provider, cc); + throw this.handleException(ex, provider, scope); } } @@ -148,7 +148,7 @@ export class GitLabApi implements Disposable { avatarSize?: number; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const [user] = await this.findUser(provider, token, email, options); @@ -163,7 +163,7 @@ export class GitLabApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, provider, cc); + throw this.handleException(ex, provider, scope); } } @@ -177,7 +177,7 @@ export class GitLabApi implements Disposable { baseUrl?: string; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { data: { @@ -208,7 +208,7 @@ export class GitLabApi implements Disposable { { fullPath: `${owner}/${repo}`, }, - cc, + scope, ); const defaultBranch = rsp?.data?.project?.repository?.rootRef ?? undefined; @@ -221,7 +221,7 @@ export class GitLabApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, provider, cc); + throw this.handleException(ex, provider, scope); } } @@ -236,7 +236,7 @@ export class GitLabApi implements Disposable { baseUrl?: string; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { data: { @@ -295,7 +295,7 @@ export class GitLabApi implements Disposable { fullPath: `${owner}/${repo}`, iid: String(number), }, - cc, + scope, ); if (rsp?.data?.project?.issue != null) { @@ -331,7 +331,7 @@ export class GitLabApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, provider, cc); + throw this.handleException(ex, provider, scope); } } @@ -348,7 +348,7 @@ export class GitLabApi implements Disposable { include?: GitLabMergeRequestState[]; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { data: { @@ -433,7 +433,7 @@ export class GitLabApi implements Disposable { branches: [branch], state: options?.include, }, - cc, + scope, ); let pr: GitLabMergeRequest | undefined; @@ -478,7 +478,7 @@ export class GitLabApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, provider, cc); + throw this.handleException(ex, provider, scope); } } @@ -494,7 +494,7 @@ export class GitLabApi implements Disposable { avatarSize?: number; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const projectId = await this.getProjectId(provider, token, owner, repo, options?.baseUrl); if (!projectId) return undefined; @@ -510,7 +510,7 @@ export class GitLabApi implements Disposable { method: 'GET', // ...options, }, - cc, + scope, ); if (mrs == null || mrs.length === 0) return undefined; @@ -527,7 +527,7 @@ export class GitLabApi implements Disposable { } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - throw this.handleException(ex, provider, cc); + throw this.handleException(ex, provider, scope); } } @@ -540,7 +540,7 @@ export class GitLabApi implements Disposable { avatarSize?: number; }, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { data: { @@ -582,7 +582,7 @@ $search: String! { search: search, }, - cc, + scope, ); const matches = rsp?.data?.users?.nodes; @@ -609,7 +609,7 @@ $search: String! } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return []; - this.handleException(ex, provider, cc); + this.handleException(ex, provider, scope); return []; } } @@ -639,7 +639,7 @@ $search: String! repo: string, baseUrl?: string, ): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); interface QueryResult { data: { project: { id: string } }; @@ -661,7 +661,7 @@ $search: String! { fullPath: `${group}/${repo}`, }, - cc, + scope, ); const gid = rsp?.data?.project?.id; @@ -672,14 +672,14 @@ $search: String! const projectId = match[1]; - if (cc != null) { - cc.exitDetails = `\u2022 projectId=${projectId}`; + if (scope != null) { + scope.exitDetails = `\u2022 projectId=${projectId}`; } return projectId; } catch (ex) { if (ex instanceof ProviderRequestNotFoundError) return undefined; - this.handleException(ex, provider, cc); + this.handleException(ex, provider, scope); return undefined; } } @@ -690,7 +690,7 @@ $search: String! baseUrl: string | undefined, query: string, variables: { [key: string]: any }, - cc: LogCorrelationContext | undefined, + scope: LogScope | undefined, ): Promise { let rsp: Response; try { @@ -727,7 +727,7 @@ $search: String! } } catch (ex) { if (ex instanceof ProviderFetchError) { - this.handleRequestError(provider, token, ex, cc); + this.handleRequestError(provider, token, ex, scope); } else if (Logger.isDebugging) { void window.showErrorMessage(`GitLab request failed: ${ex.message}`); } @@ -742,7 +742,7 @@ $search: String! baseUrl: string | undefined, route: string, options: { method: RequestInit['method'] } & Record, - cc: LogCorrelationContext | undefined, + scope: LogScope | undefined, ): Promise { const url = `${baseUrl ?? 'https://gitlab.com/api'}/${route}`; @@ -775,7 +775,7 @@ $search: String! } } catch (ex) { if (ex instanceof ProviderFetchError) { - this.handleRequestError(provider, token, ex, cc); + this.handleRequestError(provider, token, ex, scope); } else if (Logger.isDebugging) { void window.showErrorMessage(`GitLab request failed: ${ex.message}`); } @@ -788,7 +788,7 @@ $search: String! provider: RichRemoteProvider | undefined, token: string, ex: ProviderFetchError, - cc: LogCorrelationContext | undefined, + scope: LogScope | undefined, ): void { switch (ex.status) { case 404: // Not found @@ -814,7 +814,7 @@ $search: String! } throw new AuthenticationError('gitlab', AuthenticationErrorReason.Forbidden, ex); case 500: // Internal Server Error - Logger.error(ex, cc); + Logger.error(ex, scope); if (ex.response != null) { provider?.trackRequestException(); void Messages.showIntegrationRequestFailed500WarningMessage( @@ -827,7 +827,7 @@ $search: String! } return; case 502: // Bad Gateway - Logger.error(ex, cc); + Logger.error(ex, scope); // GitHub seems to return this status code for timeouts if (ex.message.includes('timeout')) { provider?.trackRequestException(); @@ -840,7 +840,7 @@ $search: String! break; } - Logger.error(ex, cc); + Logger.error(ex, scope); if (Logger.isDebugging) { void window.showErrorMessage( `GitLab request failed: ${(ex.response as any)?.errors?.[0]?.message ?? ex.message}`, @@ -848,8 +848,8 @@ $search: String! } } - private handleException(ex: Error, provider: RichRemoteProvider, cc: LogCorrelationContext | undefined): Error { - Logger.error(ex, cc); + private handleException(ex: Error, provider: RichRemoteProvider, scope: LogScope | undefined): Error { + Logger.error(ex, scope); // debugger; if (ex instanceof AuthenticationError) { diff --git a/src/plus/subscription/authenticationProvider.ts b/src/plus/subscription/authenticationProvider.ts index 1b8239f..6aef59c 100644 --- a/src/plus/subscription/authenticationProvider.ts +++ b/src/plus/subscription/authenticationProvider.ts @@ -12,7 +12,7 @@ import { uuid } from '@env/crypto'; import type { Container } from '../../container'; import { Logger } from '../../logger'; import { StorageKeys } from '../../storage'; -import { debug } from '../../system/decorators/log'; +import { debug, getLogScope } from '../../system/decorators/log'; import { ServerConnection } from './serverConnection'; interface StoredSession { @@ -64,7 +64,7 @@ export class SubscriptionAuthenticationProvider implements AuthenticationProvide @debug() public async createSession(scopes: string[]): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); // Ensure that the scopes are sorted consistently (since we use them for matching and order doesn't matter) scopes = scopes.sort(); @@ -90,7 +90,7 @@ export class SubscriptionAuthenticationProvider implements AuthenticationProvide // If login was cancelled, do not notify user. if (ex === 'Cancelled') throw ex; - Logger.error(ex, cc); + Logger.error(ex, scope); void window.showErrorMessage(`Unable to sign in to GitLens+: ${ex}`); throw ex; } @@ -98,7 +98,7 @@ export class SubscriptionAuthenticationProvider implements AuthenticationProvide @debug() async getSessions(scopes?: string[]): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); scopes = scopes?.sort(); const scopesKey = getScopesKey(scopes); @@ -106,8 +106,8 @@ export class SubscriptionAuthenticationProvider implements AuthenticationProvide const sessions = await this._sessionsPromise; const filtered = scopes != null ? sessions.filter(s => getScopesKey(s.scopes) === scopesKey) : sessions; - if (cc != null) { - cc.exitDetails = ` \u2022 Found ${filtered.length} sessions`; + if (scope != null) { + scope.exitDetails = ` \u2022 Found ${filtered.length} sessions`; } return filtered; @@ -115,7 +115,7 @@ export class SubscriptionAuthenticationProvider implements AuthenticationProvide @debug() public async removeSession(id: string) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const sessions = await this._sessionsPromise; @@ -132,7 +132,7 @@ export class SubscriptionAuthenticationProvider implements AuthenticationProvide this._onDidChangeSessions.fire({ added: [], removed: [session], changed: [] }); } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); void window.showErrorMessage(`Unable to sign out of GitLens+: ${ex}`); throw ex; } @@ -140,7 +140,7 @@ export class SubscriptionAuthenticationProvider implements AuthenticationProvide @debug() public async removeSessionsByScopes(scopes?: string[]) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { scopes = scopes?.sort(); @@ -168,7 +168,7 @@ export class SubscriptionAuthenticationProvider implements AuthenticationProvide this._onDidChangeSessions.fire({ added: [], removed: removed, changed: [] }); } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); void window.showErrorMessage(`Unable to sign out of GitLens+: ${ex}`); throw ex; } diff --git a/src/plus/subscription/serverConnection.ts b/src/plus/subscription/serverConnection.ts index 6b1bc6f..84f2e44 100644 --- a/src/plus/subscription/serverConnection.ts +++ b/src/plus/subscription/serverConnection.ts @@ -14,7 +14,7 @@ import { uuid } from '@env/crypto'; import { fetch, getProxyAgent, Response } from '@env/fetch'; import { Container } from '../../container'; import { Logger } from '../../logger'; -import { debug, log } from '../../system/decorators/log'; +import { debug, getLogScope, log } from '../../system/decorators/log'; import { memoize } from '../../system/decorators/memoize'; import { DeferredEvent, DeferredEventExecutor, promisifyDeferred } from '../../system/event'; @@ -75,7 +75,7 @@ export class ServerConnection implements Disposable { @debug({ args: false }) async getAccountInfo(token: string): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); let rsp: Response; try { @@ -88,7 +88,7 @@ export class ServerConnection implements Disposable { }, }); } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); throw ex; } diff --git a/src/plus/subscription/subscriptionService.ts b/src/plus/subscription/subscriptionService.ts index db08d0b..892faeb 100644 --- a/src/plus/subscription/subscriptionService.ts +++ b/src/plus/subscription/subscriptionService.ts @@ -44,7 +44,7 @@ import { import { executeCommand } from '../../system/command'; import { createFromDateDelta } from '../../system/date'; import { gate } from '../../system/decorators/gate'; -import { debug, log } from '../../system/decorators/log'; +import { debug, getLogScope, log } from '../../system/decorators/log'; import { memoize } from '../../system/decorators/memoize'; import { once } from '../../system/function'; import { pluralize } from '../../system/string'; @@ -327,7 +327,7 @@ export class SubscriptionService implements Disposable { async resendVerification(): Promise { if (this._subscription.account?.verified) return true; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); void this.showHomeView(true); @@ -348,7 +348,11 @@ export class SubscriptionService implements Disposable { if (!rsp.ok) { debugger; - Logger.error('', cc, `Unable to resend verification email; status=(${rsp.status}): ${rsp.statusText}`); + Logger.error( + '', + scope, + `Unable to resend verification email; status=(${rsp.status}): ${rsp.statusText}`, + ); void window.showErrorMessage(`Unable to resend verification email; Status: ${rsp.statusText}`, 'OK'); @@ -368,7 +372,7 @@ export class SubscriptionService implements Disposable { return true; } } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; void window.showErrorMessage('Unable to resend verification email', 'OK'); @@ -461,7 +465,7 @@ export class SubscriptionService implements Disposable { @gate() @log() async validate(): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const session = await this.ensureSession(false); if (session == null) { @@ -472,7 +476,7 @@ export class SubscriptionService implements Disposable { try { await this.checkInAndValidate(session); } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; } } @@ -500,7 +504,7 @@ export class SubscriptionService implements Disposable { @debug({ args: { 0: s => s?.account.label } }) private async checkInAndValidateCore(session: AuthenticationSession): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const checkInData = { @@ -533,7 +537,7 @@ export class SubscriptionService implements Disposable { this.validateSubscription(data); this._lastCheckInDate = new Date(); } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; if (ex instanceof AccountValidationError) throw ex; @@ -657,7 +661,7 @@ export class SubscriptionService implements Disposable { @debug() private async getOrCreateSession(createIfNeeded: boolean): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); let session: AuthenticationSession | null | undefined; @@ -678,7 +682,7 @@ export class SubscriptionService implements Disposable { return null; } - Logger.error(ex, cc); + Logger.error(ex, scope); } // If we didn't find a session, check if we could migrate one from the GK auth provider @@ -694,7 +698,7 @@ export class SubscriptionService implements Disposable { try { await this.checkInAndValidate(session, createIfNeeded); } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); debugger; const name = session.account.label; diff --git a/src/statusbar/statusBarController.ts b/src/statusbar/statusBarController.ts index 468d0e2..70f9002 100644 --- a/src/statusbar/statusBarController.ts +++ b/src/statusbar/statusBarController.ts @@ -18,9 +18,9 @@ import { CommitFormatter } from '../git/formatters/commitFormatter'; import type { GitCommit } from '../git/models/commit'; import type { PullRequest } from '../git/models/pullRequest'; import { Hovers } from '../hovers/hovers'; -import { LogCorrelationContext, Logger } from '../logger'; +import { Logger, LogScope } from '../logger'; import { asCommand } from '../system/command'; -import { debug } from '../system/decorators/log'; +import { debug, getLogScope } from '../system/decorators/log'; import { once } from '../system/event'; import { PromiseCancelledError } from '../system/promise'; import { isTextEditor } from '../system/utils'; @@ -179,7 +179,7 @@ export class StatusBarController implements Disposable { const cfg = configuration.get('statusBar'); if (!cfg.enabled || this._statusBarBlame == null || !isTextEditor(editor)) return; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const showPullRequests = cfg.pullRequests.enabled && @@ -214,7 +214,14 @@ export class StatusBarController implements Disposable { if (pr != null) { this._pullRequestCancellation?.cancel(); this._pullRequestCancellation = new CancellationTokenSource(); - void this.waitForPendingPullRequest(editor, commit, pr, this._pullRequestCancellation.token, timeout, cc); + void this.waitForPendingPullRequest( + editor, + commit, + pr, + this._pullRequestCancellation.token, + timeout, + scope, + ); } this._statusBarBlame.text = `$(git-commit) ${CommitFormatter.fromTemplate(cfg.format, commit, { @@ -403,18 +410,18 @@ export class StatusBarController implements Disposable { pr: PullRequest | PromiseCancelledError> | undefined, cancellationToken: CancellationToken, timeout: number, - cc: LogCorrelationContext | undefined, + scope: LogScope | undefined, ) { if (cancellationToken.isCancellationRequested || !(pr instanceof PromiseCancelledError)) return; // If the PR timed out, refresh the status bar once it completes - Logger.debug(cc, `${GlyphChars.Dot} pull request query took too long (over ${timeout} ms)`); + Logger.debug(scope, `${GlyphChars.Dot} pull request query took too long (over ${timeout} ms)`); pr = await pr.promise; if (cancellationToken.isCancellationRequested) return; - Logger.debug(cc, `${GlyphChars.Dot} pull request query completed; refreshing...`); + Logger.debug(scope, `${GlyphChars.Dot} pull request query completed; refreshing...`); void this.updateBlame(editor, commit, { pr: pr ?? null }); } diff --git a/src/system/decorators/log.ts b/src/system/decorators/log.ts index 4a9ef31..7f526b9 100644 --- a/src/system/decorators/log.ts +++ b/src/system/decorators/log.ts @@ -1,6 +1,6 @@ import { hrtime } from '@env/hrtime'; -import { LogCorrelationContext, Logger, LogLevel } from '../../logger'; -import { filterMap } from '../array'; +import type { LogScope } from '../../logger'; +import { Logger, LogLevel } from '../../logger'; import { getParameters } from '../function'; import { isPromise } from '../promise'; import { getDurationMilliseconds } from '../string'; @@ -8,30 +8,38 @@ import { getDurationMilliseconds } from '../string'; const emptyStr = ''; const maxSmallIntegerV8 = 2 ** 30; // Max number that can be stored in V8's smis (small integers) -const correlationContext = new Map(); -let correlationCounter = 0; +const scopes = new Map(); +let scopeCounter = 0; -export function getCorrelationContext() { - return correlationContext.get(correlationCounter); +export function getLogScope(): LogScope | undefined { + return scopes.get(scopeCounter); } -export function getCorrelationId() { - return correlationCounter; +export function getNewLogScope(prefix: string): LogScope { + const scopeId = getNextLogScopeId(); + return { + scopeId: scopeId, + prefix: `[${String(scopeId).padStart(5)}] ${prefix}`, + }; +} + +export function getLogScopeId(): number { + return scopeCounter; } -export function getNextCorrelationId() { - if (correlationCounter === maxSmallIntegerV8) { - correlationCounter = 0; +export function getNextLogScopeId(): number { + if (scopeCounter === maxSmallIntegerV8) { + scopeCounter = 0; } - return ++correlationCounter; + return ++scopeCounter; } -function clearCorrelationContext(correlationId: number) { - correlationContext.delete(correlationId); +function clearLogScope(scopeId: number) { + scopes.delete(scopeId); } -function setCorrelationContext(correlationId: number, context: LogCorrelationContext) { - correlationContext.set(correlationId, context); +function setLogScope(scopeId: number, scope: LogScope) { + scopes.set(scopeId, scope); } export interface LogContext { @@ -42,6 +50,27 @@ export interface LogContext { prefix: string; } +interface LogOptions any> { + args?: + | false + | { + 0?: ((arg: Parameters[0]) => unknown) | string | false; + 1?: ((arg: Parameters[1]) => unknown) | string | false; + 2?: ((arg: Parameters[2]) => unknown) | string | false; + 3?: ((arg: Parameters[3]) => unknown) | string | false; + 4?: ((arg: Parameters[4]) => unknown) | string | false; + [key: number]: (((arg: any) => unknown) | string | false) | undefined; + }; + condition?(...args: Parameters): boolean; + enter?(...args: Parameters): string; + exit?(result: PromiseType>): string; + prefix?(context: LogContext, ...args: Parameters): string; + sanitize?(key: string, value: any): any; + scoped?: boolean; + singleLine?: boolean; + timed?: boolean; +} + export const LogInstanceNameFn = Symbol('logInstanceNameFn'); export function logName(fn: (c: T, name: string) => string) { @@ -50,59 +79,41 @@ export function logName(fn: (c: T, name: string) => string) { }; } -export function debug any>( - options: { - args?: - | false - | { - 0?: ((arg: Parameters[0]) => unknown) | string | false; - 1?: ((arg: Parameters[1]) => unknown) | string | false; - 2?: ((arg: Parameters[2]) => unknown) | string | false; - 3?: ((arg: Parameters[3]) => unknown) | string | false; - 4?: ((arg: Parameters[4]) => unknown) | string | false; - [key: number]: (((arg: any) => unknown) | string | false) | undefined; - }; - condition?(...args: Parameters): boolean; - correlate?: boolean; - enter?(...args: Parameters): string; - exit?(result: PromiseType>): string; - prefix?(context: LogContext, ...args: Parameters): string; - sanitize?(key: string, value: any): any; - singleLine?: boolean; - timed?: boolean; - } = { timed: true }, -) { - return log({ debug: true, ...options }); +export function debug any>(options?: LogOptions) { + return log(options, true); } type PromiseType = T extends Promise ? U : T; -export function log any>( - options: { - args?: - | false - | { - 0?: ((arg: Parameters[0]) => unknown) | string | false; - 1?: ((arg: Parameters[1]) => unknown) | string | false; - 2?: ((arg: Parameters[2]) => unknown) | string | false; - 3?: ((arg: Parameters[3]) => unknown) | string | false; - 4?: ((arg: Parameters[4]) => unknown) | string | false; - [key: number]: (((arg: any) => unknown) | string | false) | undefined; - }; - condition?(...args: Parameters): boolean; - correlate?: boolean; - debug?: boolean; - enter?(...args: Parameters): string; - exit?(result: PromiseType>): string; - prefix?(context: LogContext, ...args: Parameters): string; - sanitize?(key: string, value: any): any; - singleLine?: boolean; - timed?: boolean; - } = { timed: true }, -) { - options = { timed: true, ...options }; - - const logFn = (options.debug ? Logger.debug.bind(Logger) : Logger.log.bind(Logger)) as +export function log any>(options?: LogOptions, debug = false) { + let overrides: LogOptions['args'] | undefined; + let conditionFn: LogOptions['condition'] | undefined; + let enterFn: LogOptions['enter'] | undefined; + let exitFn: LogOptions['exit'] | undefined; + let prefixFn: LogOptions['prefix'] | undefined; + let sanitizeFn: LogOptions['sanitize'] | undefined; + let scoped = false; + let singleLine = false; + let timed = true; + if (options != null) { + ({ + args: overrides, + condition: conditionFn, + enter: enterFn, + exit: exitFn, + prefix: prefixFn, + sanitize: sanitizeFn, + scoped = true, + singleLine = false, + timed = true, + } = options); + } + + if (timed) { + scoped = true; + } + + const logFn = (debug ? Logger.debug.bind(Logger) : Logger.log.bind(Logger)) as | typeof Logger.debug | typeof Logger.log; const warnFn = Logger.warn.bind(Logger); @@ -122,13 +133,13 @@ export function log any>( const parameters = getParameters(fn); descriptor[fnKey] = function (this: any, ...args: Parameters) { - const correlationId = getNextCorrelationId(); + const scopeId = getNextLogScopeId(); if ( (!Logger.isDebugging && !Logger.enabled(LogLevel.Debug) && - !(Logger.enabled(LogLevel.Info) && !options.debug)) || - (typeof options.condition === 'function' && !options.condition(...args)) + !(Logger.enabled(LogLevel.Info) && !debug)) || + (conditionFn != null && !conditionFn(...args)) ) { return fn!.apply(this, args); } @@ -144,19 +155,14 @@ export function log any>( instanceName = emptyStr; } - let { correlate } = options; - if (!correlate && options.timed) { - correlate = true; - } - - let prefix = `${correlate ? `[${correlationId.toString(16).padStart(5)}] ` : emptyStr}${ + let prefix = `${scoped ? `[${scopeId.toString(16).padStart(5)}] ` : emptyStr}${ instanceName ? `${instanceName}.` : emptyStr }${key}`; - if (options.prefix != null) { - prefix = options.prefix( + if (prefixFn != null) { + prefix = prefixFn( { - id: correlationId, + id: scopeId, instance: this, instanceName: instanceName, name: key, @@ -166,76 +172,84 @@ export function log any>( ); } - let correlationContext: LogCorrelationContext | undefined; - if (correlate) { - correlationContext = { correlationId: correlationId, prefix: prefix }; - setCorrelationContext(correlationId, correlationContext); + let scope: LogScope | undefined; + if (scoped) { + scope = { scopeId: scopeId, prefix: prefix }; + setLogScope(scopeId, scope); } - const enter = options.enter != null ? options.enter(...args) : emptyStr; + const enter = enterFn != null ? enterFn(...args) : emptyStr; let loggableParams: string; - if (options.args === false || args.length === 0) { + if (overrides === false || args.length === 0) { loggableParams = emptyStr; - if (!options.singleLine) { + if (!singleLine) { logFn(`${prefix}${enter}`); } } else { - const argControllers = typeof options.args === 'object' ? options.args : undefined; - let argController; - let loggable; - loggableParams = filterMap(args, (v: any, index: number) => { - const p = parameters[index]; - - argController = argControllers != null ? argControllers[index] : undefined; - if (argController != null) { - if (typeof argController === 'boolean') return undefined; - if (typeof argController === 'string') return argController; - loggable = String(argController(v)); + let loggableParams = ''; + + let paramOverride; + let paramIndex = -1; + let paramName; + let paramLogValue; + let paramValue; + + for (paramValue of args as unknown[]) { + paramName = parameters[++paramIndex]; + + paramOverride = overrides?.[paramIndex]; + if (paramOverride != null) { + if (typeof paramOverride === 'boolean') continue; + + if (loggableParams.length > 0) { + loggableParams += ', '; + } + + if (typeof paramOverride === 'string') { + loggableParams += paramOverride; + continue; + } + + paramLogValue = String(paramOverride(paramValue)); } else { - loggable = Logger.toLoggable(v, options.sanitize); + if (loggableParams.length > 0) { + loggableParams += ', '; + } + + paramLogValue = Logger.toLoggable(paramValue, sanitizeFn); } - return p ? `${p}=${loggable}` : loggable; - }).join(', '); + loggableParams += paramName ? `${paramName}=${paramLogValue}` : paramLogValue; + } - if (!options.singleLine) { + if (!singleLine) { logFn( `${prefix}${enter}`, - !options.debug && !Logger.enabled(LogLevel.Debug) && !Logger.isDebugging - ? emptyStr - : loggableParams, + !debug && !Logger.enabled(LogLevel.Debug) && !Logger.isDebugging ? emptyStr : loggableParams, ); } } - if (options.singleLine || options.timed || options.exit != null) { - const start = options.timed ? hrtime() : undefined; + if (singleLine || timed || exitFn != null) { + const start = timed ? hrtime() : undefined; const logError = (ex: Error) => { const timing = start !== undefined ? ` \u2022 ${getDurationMilliseconds(start)} ms` : emptyStr; - if (options.singleLine) { + if (singleLine) { Logger.error( ex, `${prefix}${enter}`, - `failed${ - correlationContext?.exitDetails ? correlationContext.exitDetails : emptyStr - }${timing}`, + `failed${scope?.exitDetails ? scope.exitDetails : emptyStr}${timing}`, loggableParams, ); } else { - Logger.error( - ex, - prefix, - `failed${ - correlationContext?.exitDetails ? correlationContext.exitDetails : emptyStr - }${timing}`, - ); + Logger.error(ex, prefix, `failed${scope?.exitDetails ? scope.exitDetails : emptyStr}${timing}`); } - if (correlate) { - clearCorrelationContext(correlationId); + if (scoped) { + clearLogScope(scopeId); } }; @@ -265,9 +279,9 @@ export function log any>( } let exit; - if (options.exit != null) { + if (exitFn != null) { try { - exit = options.exit(r); + exit = exitFn(r); } catch (ex) { exit = `@log.exit error: ${ex}`; } @@ -275,25 +289,19 @@ export function log any>( exit = 'completed'; } - if (options.singleLine) { + if (singleLine) { exitLogFn( - `${prefix}${enter} ${exit}${ - correlationContext?.exitDetails ? correlationContext.exitDetails : emptyStr - }${timing}`, - !options.debug && !Logger.enabled(LogLevel.Debug) && !Logger.isDebugging + `${prefix}${enter} ${exit}${scope?.exitDetails ? scope.exitDetails : emptyStr}${timing}`, + !debug && !Logger.enabled(LogLevel.Debug) && !Logger.isDebugging ? emptyStr : loggableParams, ); } else { - exitLogFn( - `${prefix} ${exit}${ - correlationContext?.exitDetails ? correlationContext.exitDetails : emptyStr - }${timing}`, - ); + exitLogFn(`${prefix} ${exit}${scope?.exitDetails ? scope.exitDetails : emptyStr}${timing}`); } - if (correlate) { - clearCorrelationContext(correlationId); + if (scoped) { + clearLogScope(scopeId); } }; diff --git a/src/system/stopwatch.ts b/src/system/stopwatch.ts index 22f53be..1c45540 100644 --- a/src/system/stopwatch.ts +++ b/src/system/stopwatch.ts @@ -1,7 +1,7 @@ import { hrtime } from '@env/hrtime'; import { GlyphChars } from '../constants'; -import { LogCorrelationContext, Logger, LogLevel } from '../logger'; -import { getNextCorrelationId } from '../system/decorators/log'; +import { Logger, LogLevel, LogScope } from '../logger'; +import { getNextLogScopeId } from '../system/decorators/log'; type StopwatchLogOptions = { message?: string; suffix?: string }; type StopwatchOptions = { @@ -11,15 +11,15 @@ type StopwatchOptions = { type StopwatchLogLevel = Exclude; export class Stopwatch { - private readonly instance = `[${String(getNextCorrelationId()).padStart(5)}] `; + private readonly instance = `[${String(getNextLogScopeId()).padStart(5)}] `; private readonly logLevel: StopwatchLogLevel; private time: [number, number]; - constructor(public readonly context: string | LogCorrelationContext, options?: StopwatchOptions, ...params: any[]) { - let cc; - if (typeof context !== 'string') { - cc = context; - context = ''; + constructor(public readonly scope: string | LogScope | undefined, options?: StopwatchOptions, ...params: any[]) { + let logScope; + if (typeof scope !== 'string') { + logScope = scope; + scope = ''; this.instance = ''; } @@ -39,26 +39,26 @@ export class Stopwatch { if (params.length) { log( this.logLevel, - cc, - `${this.instance}${context}${logOptions.message ?? ''}${logOptions.suffix ?? ''}`, + logScope, + `${this.instance}${scope}${logOptions.message ?? ''}${logOptions.suffix ?? ''}`, ...params, ); } else { log( this.logLevel, - cc, - `${this.instance}${context}${logOptions.message ?? ''}${logOptions.suffix ?? ''}`, + logScope, + `${this.instance}${scope}${logOptions.message ?? ''}${logOptions.suffix ?? ''}`, ); } } } log(options?: StopwatchLogOptions): void { - this.logCore(this.context, options, false); + this.logCore(this.scope, options, false); } restart(options?: StopwatchLogOptions): void { - this.logCore(this.context, options, true); + this.logCore(this.scope, options, true); this.time = hrtime(); } @@ -67,20 +67,20 @@ export class Stopwatch { } private logCore( - context: string | LogCorrelationContext, + scope: string | LogScope | undefined, options: StopwatchLogOptions | undefined, logTotalElapsed: boolean, ): void { if (!Logger.enabled(this.logLevel)) return; - let cc; - if (typeof context !== 'string') { - cc = context; - context = ''; + let logScope; + if (typeof scope !== 'string') { + logScope = scope; + scope = ''; } if (!logTotalElapsed) { - log(this.logLevel, cc, `${this.instance}${context}${options?.message ?? ''}${options?.suffix ?? ''}`); + log(this.logLevel, logScope, `${this.instance}${scope}${options?.message ?? ''}${options?.suffix ?? ''}`); return; } @@ -88,10 +88,10 @@ export class Stopwatch { const [secs, nanosecs] = hrtime(this.time); const ms = secs * 1000 + Math.floor(nanosecs / 1000000); - const prefix = `${this.instance}${context}${options?.message ?? ''}`; + const prefix = `${this.instance}${scope}${options?.message ?? ''}`; log( ms > 250 ? LogLevel.Warn : this.logLevel, - cc, + logScope, `${prefix ? `${prefix} ${GlyphChars.Dot} ` : ''}${ms} ms${options?.suffix ?? ''}`, ); } @@ -113,19 +113,19 @@ export class Stopwatch { } } -function log(logLevel: StopwatchLogLevel, cc: LogCorrelationContext | undefined, message: string, ...params: any[]) { +function log(logLevel: StopwatchLogLevel, scope: LogScope | undefined, message: string, ...params: any[]) { switch (logLevel) { case LogLevel.Error: - Logger.error('', cc, message, ...params); + Logger.error('', scope, message, ...params); break; case LogLevel.Warn: - Logger.warn(cc, message, ...params); + Logger.warn(scope, message, ...params); break; case LogLevel.Info: - Logger.log(cc, message, ...params); + Logger.log(scope, message, ...params); break; default: - Logger.debug(cc, message, ...params); + Logger.debug(scope, message, ...params); break; } } diff --git a/src/trackers/gitLineTracker.ts b/src/trackers/gitLineTracker.ts index b877cee..20229db 100644 --- a/src/trackers/gitLineTracker.ts +++ b/src/trackers/gitLineTracker.ts @@ -3,8 +3,7 @@ import { configuration } from '../configuration'; import { GlyphChars } from '../constants'; import type { Container } from '../container'; import type { GitCommit } from '../git/models/commit'; -import { Logger } from '../logger'; -import { debug } from '../system/decorators/log'; +import { debug, getLogScope } from '../system/decorators/log'; import type { DocumentBlameStateChangeEvent, DocumentContentChangeEvent, @@ -83,11 +82,11 @@ export class GitLineTracker extends LineTracker { }) private onContentChanged(e: DocumentContentChangeEvent) { if ( - e.contentChanges.some(cc => + e.contentChanges.some(scope => this.selections?.some( selection => - (cc.range.end.line >= selection.active && selection.active >= cc.range.start.line) || - (cc.range.start.line >= selection.active && selection.active >= cc.range.end.line), + (scope.range.end.line >= selection.active && selection.active >= scope.range.start.line) || + (scope.range.start.line >= selection.active && selection.active >= scope.range.end.line), ), ) ) { @@ -128,11 +127,11 @@ export class GitLineTracker extends LineTracker { exit: updated => `returned ${updated}`, }) private async updateState(selections: LineSelection[], editor: TextEditor): Promise { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); if (!this.includes(selections)) { - if (cc != null) { - cc.exitDetails = ` ${GlyphChars.Dot} lines no longer match`; + if (scope != null) { + scope.exitDetails = ` ${GlyphChars.Dot} lines no longer match`; } return false; @@ -140,8 +139,8 @@ export class GitLineTracker extends LineTracker { const trackedDocument = await this.container.tracker.getOrAdd(editor.document); if (!trackedDocument.isBlameable) { - if (cc != null) { - cc.exitDetails = ` ${GlyphChars.Dot} document is not blameable`; + if (scope != null) { + scope.exitDetails = ` ${GlyphChars.Dot} document is not blameable`; } return false; @@ -154,8 +153,8 @@ export class GitLineTracker extends LineTracker { editor?.document, ); if (blameLine == null) { - if (cc != null) { - cc.exitDetails = ` ${GlyphChars.Dot} blame failed`; + if (scope != null) { + scope.exitDetails = ` ${GlyphChars.Dot} blame failed`; } return false; @@ -165,8 +164,8 @@ export class GitLineTracker extends LineTracker { } else { const blame = await this.container.git.getBlame(trackedDocument.uri, editor.document); if (blame == null) { - if (cc != null) { - cc.exitDetails = ` ${GlyphChars.Dot} blame failed`; + if (scope != null) { + scope.exitDetails = ` ${GlyphChars.Dot} blame failed`; } return false; @@ -181,16 +180,16 @@ export class GitLineTracker extends LineTracker { // Check again because of the awaits above if (!this.includes(selections)) { - if (cc != null) { - cc.exitDetails = ` ${GlyphChars.Dot} lines no longer match`; + if (scope != null) { + scope.exitDetails = ` ${GlyphChars.Dot} lines no longer match`; } return false; } if (!trackedDocument.isBlameable) { - if (cc != null) { - cc.exitDetails = ` ${GlyphChars.Dot} document is not blameable`; + if (scope != null) { + scope.exitDetails = ` ${GlyphChars.Dot} document is not blameable`; } return false; diff --git a/src/trackers/lineTracker.ts b/src/trackers/lineTracker.ts index 429863c..fe573d8 100644 --- a/src/trackers/lineTracker.ts +++ b/src/trackers/lineTracker.ts @@ -1,6 +1,6 @@ import { Disposable, Event, EventEmitter, Selection, TextEditor, TextEditorSelectionChangeEvent, window } from 'vscode'; import { Logger } from '../logger'; -import { debug } from '../system/decorators/log'; +import { debug, getLogScope } from '../system/decorators/log'; import { debounce, Deferrable } from '../system/function'; import { isTextEditor } from '../system/utils'; @@ -115,7 +115,7 @@ export class LineTracker implements Disposable { @debug({ args: false }) subscribe(subscriber: unknown, subscription: Disposable): Disposable { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); const disposable = { dispose: () => this.unsubscribe(subscriber), @@ -132,7 +132,7 @@ export class LineTracker implements Disposable { } if (first) { - Logger.debug(cc, 'Starting line tracker...'); + Logger.debug(scope, 'Starting line tracker...'); this._disposable = Disposable.from( window.onDidChangeActiveTextEditor(debounce(this.onActiveTextEditorChanged, 0), this), diff --git a/src/views/nodes/fileHistoryTrackerNode.ts b/src/views/nodes/fileHistoryTrackerNode.ts index 55b139b..78ea1b4 100644 --- a/src/views/nodes/fileHistoryTrackerNode.ts +++ b/src/views/nodes/fileHistoryTrackerNode.ts @@ -7,7 +7,7 @@ import { GitReference, GitRevision } from '../../git/models/reference'; import { Logger } from '../../logger'; import { ReferencePicker } from '../../quickpicks/referencePicker'; import { gate } from '../../system/decorators/gate'; -import { debug, log } from '../../system/decorators/log'; +import { debug, getLogScope, log } from '../../system/decorators/log'; import { debounce, Deferrable } from '../../system/function'; import { isVirtualUri } from '../../system/utils'; import type { FileHistoryView } from '../fileHistoryView'; @@ -131,7 +131,7 @@ export class FileHistoryTrackerNode extends SubscribeableViewNode `returned ${r}`, }) override async refresh(reset: boolean = false) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); if (!this.canSubscribe) return false; @@ -155,15 +155,15 @@ export class FileHistoryTrackerNode extends SubscribeableViewNode `returned ${r}`, }) override async refresh(reset: boolean = false) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); if (!this.canSubscribe) return false; @@ -166,8 +166,8 @@ export class LineHistoryTrackerNode extends SubscribeableViewNode { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); async function find(this: ViewBase) { try { @@ -384,7 +384,7 @@ export abstract class ViewBase< return node; } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); return undefined; } } @@ -537,12 +537,12 @@ export abstract class ViewBase< @log() async show(options?: { preserveFocus?: boolean }) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { void (await executeCommand(`${this.id}.focus`, options)); } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); } } diff --git a/src/vsls/guest.ts b/src/vsls/guest.ts index d8c9401..74248fa 100644 --- a/src/vsls/guest.ts +++ b/src/vsls/guest.ts @@ -3,14 +3,14 @@ import type { LiveShare, SharedServiceProxy } from '../@types/vsls'; import { Container } from '../container'; import { GitCommandOptions } from '../git/commandOptions'; import { Logger } from '../logger'; -import { debug, log } from '../system/decorators/log'; +import { debug, getLogScope, log } from '../system/decorators/log'; import { VslsHostService } from './host'; import { GetRepositoriesForUriRequestType, GitCommandRequestType, RepositoryProxy, RequestType } from './protocol'; export class VslsGuestService implements Disposable { @log() static async connect(api: LiveShare, container: Container) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { const service = await api.getSharedService(VslsHostService.ServiceId); @@ -20,7 +20,7 @@ export class VslsGuestService implements Disposable { return new VslsGuestService(api, service, container); } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); return undefined; } } diff --git a/src/vsls/host.ts b/src/vsls/host.ts index 574092f..c7aeaa3 100644 --- a/src/vsls/host.ts +++ b/src/vsls/host.ts @@ -3,7 +3,7 @@ import { git } from '@env/providers'; import type { LiveShare, SharedService } from '../@types/vsls'; import { Container } from '../container'; import { Logger } from '../logger'; -import { debug, log } from '../system/decorators/log'; +import { debug, getLogScope, log } from '../system/decorators/log'; import { join } from '../system/iterable'; import { isVslsRoot, normalizePath } from '../system/path'; import { @@ -103,7 +103,7 @@ export class VslsHostService implements Disposable { private onWorkspaceFoldersChanged(_e?: WorkspaceFoldersChangeEvent) { if (workspace.workspaceFolders == null || workspace.workspaceFolders.length === 0) return; - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); this._localToSharedPaths.clear(); this._sharedToLocalPaths.clear(); @@ -114,7 +114,7 @@ export class VslsHostService implements Disposable { localPath = normalizePath(f.uri.fsPath); sharedPath = normalizePath(this.convertLocalUriToShared(f.uri).toString()); - Logger.debug(cc, `shared='${sharedPath}' \u2194 local='${localPath}'`); + Logger.debug(scope, `shared='${sharedPath}' \u2194 local='${localPath}'`); this._localToSharedPaths.set(localPath, sharedPath); this._sharedToLocalPaths.set(sharedPath, localPath); } @@ -233,11 +233,11 @@ export class VslsHostService implements Disposable { exit: result => `returned ${result.toString(true)}`, }) private convertLocalUriToShared(localUri: Uri) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); let sharedUri = this._api.convertLocalUriToShared(localUri); Logger.debug( - cc, + scope, `LiveShare.convertLocalUriToShared(${localUri.toString(true)}) returned ${sharedUri.toString(true)}`, ); diff --git a/src/webviews/webviewViewBase.ts b/src/webviews/webviewViewBase.ts index 6d836a5..c4083d1 100644 --- a/src/webviews/webviewViewBase.ts +++ b/src/webviews/webviewViewBase.ts @@ -15,7 +15,7 @@ import { Commands } from '../constants'; import type { Container } from '../container'; import { Logger } from '../logger'; import { executeCommand } from '../system/command'; -import { log } from '../system/decorators/log'; +import { getLogScope, log } from '../system/decorators/log'; import { ExecuteCommandType, IpcMessage, @@ -85,12 +85,12 @@ export abstract class WebviewViewBase implements WebviewViewProvider, Dis @log() async show(options?: { preserveFocus?: boolean }) { - const cc = Logger.getCorrelationContext(); + const scope = getLogScope(); try { void (await executeCommand(`${this.id}.focus`, options)); } catch (ex) { - Logger.error(ex, cc); + Logger.error(ex, scope); } }