refactor(logging): Centralize console logging with debugLogger (#11590)

This commit is contained in:
Abhi
2025-10-21 16:35:22 -04:00
committed by GitHub
parent f5e07d94bd
commit b364f37655
72 changed files with 345 additions and 289 deletions

View File

@@ -4,6 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { debugLogger } from '@google/gemini-cli-core';
import { execSync } from 'node:child_process';
import { ProxyAgent } from 'undici';
@@ -24,7 +25,7 @@ export const isGitHubRepository = (): boolean => {
return pattern.test(remotes);
} catch (_error) {
// If any filesystem error occurs, assume not a git repo
console.debug(`Failed to get git remote:`, _error);
debugLogger.debug(`Failed to get git remote:`, _error);
return false;
}
};
@@ -83,7 +84,10 @@ export const getLatestGitHubRelease = async (
}
return releaseTag;
} catch (_error) {
console.debug(`Failed to determine latest run-gemini-cli release:`, _error);
debugLogger.debug(
`Failed to determine latest run-gemini-cli release:`,
_error,
);
throw new Error(
`Unable to determine the latest run-gemini-cli release on GitHub.`,
);

View File

@@ -9,10 +9,16 @@ import { getInstallationInfo, PackageManager } from './installationInfo.js';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as childProcess from 'node:child_process';
import { isGitRepository } from '@google/gemini-cli-core';
import { isGitRepository, debugLogger } from '@google/gemini-cli-core';
vi.mock('@google/gemini-cli-core', () => ({
isGitRepository: vi.fn(),
debugLogger: {
log: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
},
}));
vi.mock('fs', async (importOriginal) => {
@@ -59,7 +65,6 @@ describe('getInstallationInfo', () => {
});
it('should return UNKNOWN and log error if realpathSync fails', () => {
const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
process.argv[1] = '/path/to/cli';
const error = new Error('realpath failed');
mockedRealPathSync.mockImplementation(() => {
@@ -69,8 +74,7 @@ describe('getInstallationInfo', () => {
const info = getInstallationInfo(projectRoot, false);
expect(info.packageManager).toBe(PackageManager.UNKNOWN);
expect(consoleSpy).toHaveBeenCalledWith(error);
consoleSpy.mockRestore();
expect(debugLogger.log).toHaveBeenCalledWith(error);
});
it('should detect running from a local git clone', () => {

View File

@@ -4,7 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { isGitRepository } from '@google/gemini-cli-core';
import { debugLogger, isGitRepository } from '@google/gemini-cli-core';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as childProcess from 'node:child_process';
@@ -174,7 +174,7 @@ export function getInstallationInfo(
: 'Installed with npm. Attempting to automatically update now...',
};
} catch (error) {
console.log(error);
debugLogger.log(error);
return { packageManager: PackageManager.UNKNOWN, isGlobal: false };
}
}

View File

@@ -4,6 +4,8 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { debugLogger } from '@google/gemini-cli-core';
export async function readStdin(): Promise<string> {
const MAX_STDIN_SIZE = 8 * 1024 * 1024; // 8MB
return new Promise((resolve, reject) => {
@@ -30,7 +32,7 @@ export async function readStdin(): Promise<string> {
if (totalSize + chunk.length > MAX_STDIN_SIZE) {
const remainingSize = MAX_STDIN_SIZE - totalSize;
data += chunk.slice(0, remainingSize);
console.warn(
debugLogger.warn(
`Warning: stdin input truncated to ${MAX_STDIN_SIZE} bytes.`,
);
process.stdin.destroy(); // Stop reading further

View File

@@ -14,7 +14,11 @@ import { quote, parse } from 'shell-quote';
import { USER_SETTINGS_DIR } from '../config/settings.js';
import { promisify } from 'node:util';
import type { Config, SandboxConfig } from '@google/gemini-cli-core';
import { FatalSandboxError, GEMINI_DIR } from '@google/gemini-cli-core';
import {
debugLogger,
FatalSandboxError,
GEMINI_DIR,
} from '@google/gemini-cli-core';
import { ConsolePatcher } from '../ui/utils/ConsolePatcher.js';
import { randomBytes } from 'node:crypto';
@@ -92,7 +96,7 @@ async function shouldUseCurrentUserInSandbox(): Promise<boolean> {
} catch (_err) {
// Silently ignore if /etc/os-release is not found or unreadable.
// The default (false) will be applied in this case.
console.warn(
debugLogger.warn(
'Warning: Could not read /etc/os-release to auto-detect Debian/Ubuntu for UID/GID default.',
);
}
@@ -301,7 +305,7 @@ export async function start_sandbox(
});
// install handlers to stop proxy on exit/signal
const stopProxy = () => {
console.log('stopping proxy ...');
debugLogger.log('stopping proxy ...');
if (proxyProcess?.pid) {
process.kill(-proxyProcess.pid, 'SIGTERM');
}
@@ -325,7 +329,7 @@ export async function start_sandbox(
`Proxy command '${proxyCommand}' exited with code ${code}, signal ${signal}`,
);
});
console.log('waiting for proxy to start ...');
debugLogger.log('waiting for proxy to start ...');
await execAsync(
`until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`,
);
@@ -559,7 +563,7 @@ export async function start_sandbox(
containerName = `gemini-cli-integration-test-${randomBytes(4).toString(
'hex',
)}`;
console.log(`ContainerName: ${containerName}`);
debugLogger.log(`ContainerName: ${containerName}`);
} else {
let index = 0;
const containerNameCheck = execSync(
@@ -571,7 +575,7 @@ export async function start_sandbox(
index++;
}
containerName = `${imageName}-${index}`;
console.log(`ContainerName (regular): ${containerName}`);
debugLogger.log(`ContainerName (regular): ${containerName}`);
}
args.push('--name', containerName, '--hostname', containerName);
@@ -773,7 +777,7 @@ export async function start_sandbox(
});
// install handlers to stop proxy on exit/signal
const stopProxy = () => {
console.log('stopping proxy container ...');
debugLogger.log('stopping proxy container ...');
execSync(`${config.command} rm -f ${SANDBOX_PROXY_NAME}`);
};
process.on('exit', stopProxy);
@@ -795,7 +799,7 @@ export async function start_sandbox(
`Proxy container command '${proxyContainerCommand}' exited with code ${code}, signal ${signal}`,
);
});
console.log('waiting for proxy to start ...');
debugLogger.log('waiting for proxy to start ...');
await execAsync(
`until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`,
);
@@ -821,7 +825,7 @@ export async function start_sandbox(
sandboxProcess?.on('close', (code, signal) => {
process.stdin.resume();
if (code !== 0 && code !== null) {
console.log(
debugLogger.log(
`Sandbox process exited with code: ${code}, signal: ${signal}`,
);
}
@@ -847,7 +851,7 @@ async function imageExists(sandbox: string, image: string): Promise<boolean> {
}
checkProcess.on('error', (err) => {
console.warn(
debugLogger.warn(
`Failed to start '${sandbox}' command for image check: ${err.message}`,
);
resolve(false);
@@ -882,7 +886,7 @@ async function pullImage(sandbox: string, image: string): Promise<boolean> {
};
const onError = (err: Error) => {
console.warn(
debugLogger.warn(
`Failed to start '${sandbox} pull ${image}' command: ${err.message}`,
);
cleanup();
@@ -895,7 +899,7 @@ async function pullImage(sandbox: string, image: string): Promise<boolean> {
cleanup();
resolve(true);
} else {
console.warn(
debugLogger.warn(
`Failed to pull image ${image}. '${sandbox} pull ${image}' exited with code ${code}.`,
);
if (stderrData.trim()) {
@@ -953,7 +957,7 @@ async function ensureSandboxImageIsPresent(
console.info(`Sandbox image ${image} is now available after pulling.`);
return true;
} else {
console.warn(
debugLogger.warn(
`Sandbox image ${image} still not found after a pull attempt. This might indicate an issue with the image name or registry, or the pull command reported success but failed to make the image available.`,
);
return false;

View File

@@ -6,7 +6,7 @@
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import { type Config } from '@google/gemini-cli-core';
import { debugLogger, type Config } from '@google/gemini-cli-core';
import type { Settings, SessionRetentionSettings } from '../config/settings.js';
import { getAllSessionFiles, type SessionFileEntry } from './sessionUtils.js';
@@ -88,11 +88,11 @@ export async function cleanupExpiredSessions(
if (config.getDebugMode()) {
if (sessionToDelete.sessionInfo === null) {
console.debug(
debugLogger.debug(
`Deleted corrupted session file: ${sessionToDelete.fileName}`,
);
} else {
console.debug(
debugLogger.debug(
`Deleted expired session: ${sessionToDelete.sessionInfo.id} (${sessionToDelete.sessionInfo.lastUpdated})`,
);
}
@@ -125,7 +125,7 @@ export async function cleanupExpiredSessions(
result.skipped = result.scanned - result.deleted - result.failed;
if (config.getDebugMode() && result.deleted > 0) {
console.debug(
debugLogger.debug(
`Session cleanup: deleted ${result.deleted}, skipped ${result.skipped}, failed ${result.failed}`,
);
}