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
+4 -3
View File
@@ -42,6 +42,7 @@ import {
AuthType,
clearCachedCredentialFile,
ShellExecutionService,
debugLogger,
} from '@google/gemini-cli-core';
import { validateAuthMethod } from '../config/auth.js';
import { loadHierarchicalGeminiMemory } from '../config/config.js';
@@ -389,7 +390,7 @@ export const AppContainer = (props: AppContainerProps) => {
config.isBrowserLaunchSuppressed()
) {
await runExitCleanup();
console.log(`
debugLogger.log(`
----------------------------------------------------------------
Logging in with Google... Please restart Gemini CLI to continue.
----------------------------------------------------------------
@@ -558,7 +559,7 @@ Logging in with Google... Please restart Gemini CLI to continue.
Date.now(),
);
if (config.getDebugMode()) {
console.log(
debugLogger.log(
`[DEBUG] Refreshed memory content in config: ${memoryContent.substring(
0,
200,
@@ -933,7 +934,7 @@ Logging in with Google... Please restart Gemini CLI to continue.
(key: Key) => {
// Debug log keystrokes if enabled
if (settings.merged.general?.debugKeystrokeLogging) {
console.log('[DEBUG] Keystroke:', JSON.stringify(key));
debugLogger.log('[DEBUG] Keystroke:', JSON.stringify(key));
}
if (keyMatchers[Command.QUIT](key)) {
+2 -1
View File
@@ -14,6 +14,7 @@ import { SettingScope } from '../../config/settings.js';
import {
AuthType,
clearCachedCredentialFile,
debugLogger,
type Config,
} from '@google/gemini-cli-core';
import { useKeypress } from '../hooks/useKeypress.js';
@@ -108,7 +109,7 @@ export function AuthDialog({
config.isBrowserLaunchSuppressed()
) {
runExitCleanup();
console.log(
debugLogger.log(
`
----------------------------------------------------------------
Logging in with Google... Please restart Gemini CLI to continue.
+2 -2
View File
@@ -6,7 +6,7 @@
import { useState, useEffect, useCallback } from 'react';
import type { LoadedSettings } from '../../config/settings.js';
import { AuthType, type Config } from '@google/gemini-cli-core';
import { AuthType, debugLogger, type Config } from '@google/gemini-cli-core';
import { getErrorMessage } from '@google/gemini-cli-core';
import { AuthState } from '../types.js';
import { validateAuthMethod } from '../../config/auth.js';
@@ -80,7 +80,7 @@ export const useAuthCommand = (settings: LoadedSettings, config: Config) => {
try {
await config.refreshAuth(authType);
console.log(`Authenticated via "${authType}".`);
debugLogger.log(`Authenticated via "${authType}".`);
setAuthError(null);
setAuthState(AuthState.Authenticated);
} catch (e) {
+2 -1
View File
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { debugLogger } from '@google/gemini-cli-core';
import { copyToClipboard } from '../utils/commandUtils.js';
import type { SlashCommand, SlashCommandActionReturn } from './types.js';
import { CommandKind } from './types.js';
@@ -45,7 +46,7 @@ export const copyCommand: SlashCommand = {
};
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.debug(message);
debugLogger.debug(message);
return {
type: 'message',
@@ -20,6 +20,7 @@ import {
import type { SlashCommand, SlashCommandActionReturn } from './types.js';
import { CommandKind } from './types.js';
import { getUrlOpenCommand } from '../../ui/utils/commandUtils.js';
import { debugLogger } from '@google/gemini-cli-core';
export const GITHUB_WORKFLOW_PATHS = [
'gemini-dispatch/gemini-dispatch.yml',
@@ -84,7 +85,7 @@ export async function updateGitignore(gitRepoRoot: string): Promise<void> {
}
}
} catch (error) {
console.debug('Failed to update .gitignore:', error);
debugLogger.debug('Failed to update .gitignore:', error);
// Continue without failing the whole command
}
}
@@ -109,7 +110,7 @@ export const setupGithubCommand: SlashCommand = {
try {
gitRepoRoot = getGitRepoRoot();
} catch (_error) {
console.debug(`Failed to get git repo root:`, _error);
debugLogger.debug(`Failed to get git repo root:`, _error);
throw new Error(
'Unable to determine the GitHub repository. /setup-github must be run from a git repository.',
);
@@ -125,7 +126,7 @@ export const setupGithubCommand: SlashCommand = {
try {
await fs.promises.mkdir(githubWorkflowsDir, { recursive: true });
} catch (_error) {
console.debug(
debugLogger.debug(
`Failed to create ${githubWorkflowsDir} directory:`,
_error,
);
@@ -37,6 +37,7 @@ import {
type SettingsValue,
TOGGLE_TYPES,
} from '../../config/settingsSchema.js';
import { debugLogger } from '@google/gemini-cli-core';
interface SettingsDialogProps {
settings: LoadedSettings;
@@ -162,7 +163,7 @@ export function SettingsDialog({
newValue,
currentScopeSettings,
);
console.log(
debugLogger.log(
`[DEBUG SettingsDialog] Saving ${key} immediately with value:`,
newValue,
);
@@ -207,7 +208,7 @@ export function SettingsDialog({
setModifiedSettings((prev) => {
const updated = new Set(prev).add(key);
const needsRestart = hasRestartRequiredSettings(updated);
console.log(
debugLogger.log(
`[DEBUG SettingsDialog] Modified settings:`,
Array.from(updated),
'Needs restart:',
@@ -9,6 +9,7 @@ import * as path from 'node:path';
import type { PartListUnion, PartUnion } from '@google/genai';
import type { AnyToolInvocation, Config } from '@google/gemini-cli-core';
import {
debugLogger,
getErrorMessage,
isNodeError,
unescapePath,
@@ -372,7 +373,7 @@ export async function handleAtCommand({
}
const message = `Ignored ${totalIgnored} files:\n${messages.join('\n')}`;
console.log(message);
debugLogger.log(message);
onDebugMessage(message);
}
@@ -222,8 +222,6 @@ export const useShellCommandProcessor = (
shellExecutionConfig,
);
console.log(terminalHeight, terminalWidth);
executionPid = pid;
if (pid) {
setActiveShellPtyId(pid);
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { debugLogger } from '@google/gemini-cli-core';
import { useState, useCallback } from 'react';
interface Logger {
@@ -69,7 +70,10 @@ export function useInputHistoryStore(): UseInputHistoryStoreReturn {
setIsInitialized(true);
} catch (error) {
// Start with empty history even if logger initialization fails
console.warn('Failed to initialize input history from logger:', error);
debugLogger.warn(
'Failed to initialize input history from logger:',
error,
);
setPastSessionMessages([]);
recalculateHistory([], []);
setIsInitialized(true);
@@ -20,7 +20,7 @@ import type {
Status as CoreStatus,
EditorType,
} from '@google/gemini-cli-core';
import { CoreToolScheduler } from '@google/gemini-cli-core';
import { CoreToolScheduler, debugLogger } from '@google/gemini-cli-core';
import { useCallback, useState, useMemo } from 'react';
import type {
HistoryItemToolGroup,
@@ -198,7 +198,7 @@ function mapCoreStatusToDisplayStatus(coreStatus: CoreStatus): ToolCallStatus {
return ToolCallStatus.Pending;
default: {
const exhaustiveCheck: never = coreStatus;
console.warn(`Unknown core status encountered: ${exhaustiveCheck}`);
debugLogger.warn(`Unknown core status encountered: ${exhaustiveCheck}`);
return ToolCallStatus.Error;
}
}
@@ -6,7 +6,7 @@
import type { Message } from '../types.js';
import { MessageType } from '../types.js';
import type { Config } from '@google/gemini-cli-core';
import { debugLogger, type Config } from '@google/gemini-cli-core';
import type { LoadedSettings } from '../../config/settings.js';
export function createShowMemoryAction(
@@ -27,7 +27,7 @@ export function createShowMemoryAction(
const debugMode = config.getDebugMode();
if (debugMode) {
console.log('[DEBUG] Show Memory command invoked.');
debugLogger.log('[DEBUG] Show Memory command invoked.');
}
const currentMemory = config.getUserMemory();
@@ -38,10 +38,10 @@ export function createShowMemoryAction(
: [contextFileName];
if (debugMode) {
console.log(
debugLogger.log(
`[DEBUG] Showing memory. Content from config.getUserMemory() (first 200 chars): ${currentMemory.substring(0, 200)}...`,
);
console.log(`[DEBUG] Number of context files loaded: ${fileCount}`);
debugLogger.log(`[DEBUG] Number of context files loaded: ${fileCount}`);
}
if (fileCount > 0) {
@@ -12,6 +12,7 @@ import {
type CommandContext,
type SlashCommand,
} from '../commands/types.js';
import { debugLogger } from '@google/gemini-cli-core';
// Type alias for improved type safety based on actual fzf result structure
type FzfCommandResult = {
@@ -189,7 +190,7 @@ function useCommandSuggestions(
// Safety check: ensure leafCommand and completion exist
if (!leafCommand?.completion) {
console.warn(
debugLogger.warn(
'Attempted argument completion without completion function',
);
return;
+2 -1
View File
@@ -8,6 +8,7 @@ import { useCallback, useReducer, useEffect } from 'react';
import type { Key } from './useKeypress.js';
import type { TextBuffer } from '../components/shared/text-buffer.js';
import { useVimMode } from '../contexts/VimModeContext.js';
import { debugLogger } from '@google/gemini-cli-core';
export type VimMode = 'NORMAL' | 'INSERT';
@@ -394,7 +395,7 @@ export function useVim(buffer: TextBuffer, onSubmit?: (value: string) => void) {
normalizedKey = normalizeKey(key);
} catch (error) {
// Handle malformed key inputs gracefully
console.warn('Malformed key input in vim mode:', key, error);
debugLogger.warn('Malformed key input in vim mode:', key, error);
return false;
}
+3 -1
View File
@@ -4,6 +4,8 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { debugLogger } from '@google/gemini-cli-core';
// Mapping from common CSS color names (lowercase) to hex codes (lowercase)
// Excludes names directly supported by Ink
export const CSS_NAME_TO_HEX_MAP: Readonly<Record<string, string>> = {
@@ -224,7 +226,7 @@ export function resolveColor(colorValue: string): string | undefined {
}
// 4. Could not resolve
console.warn(
debugLogger.warn(
`[ColorUtils] Could not resolve color "${colorValue}" to an Ink-compatible format.`,
);
return undefined;
+11 -7
View File
@@ -25,6 +25,7 @@ import { ANSI } from './ansi.js';
import { ANSILight } from './ansi-light.js';
import { NoColorTheme } from './no-color.js';
import process from 'node:process';
import { debugLogger } from '@google/gemini-cli-core';
export interface ThemeDisplay {
name: string;
@@ -75,7 +76,7 @@ class ThemeManager {
const validation = validateCustomTheme(customThemeConfig);
if (validation.isValid) {
if (validation.warning) {
console.warn(`Theme "${name}": ${validation.warning}`);
debugLogger.warn(`Theme "${name}": ${validation.warning}`);
}
const themeWithDefaults: CustomTheme = {
...DEFAULT_THEME.colors,
@@ -88,10 +89,10 @@ class ThemeManager {
const theme = createCustomTheme(themeWithDefaults);
this.customThemes.set(name, theme);
} catch (error) {
console.warn(`Failed to load custom theme "${name}":`, error);
debugLogger.warn(`Failed to load custom theme "${name}":`, error);
}
} else {
console.warn(`Invalid custom theme "${name}": ${validation.error}`);
debugLogger.warn(`Invalid custom theme "${name}": ${validation.error}`);
}
}
// If the current active theme is a custom theme, keep it if still valid
@@ -246,7 +247,7 @@ class ThemeManager {
// 2. Perform security check.
const homeDir = path.resolve(os.homedir());
if (!canonicalPath.startsWith(homeDir)) {
console.warn(
debugLogger.warn(
`Theme file at "${themePath}" is outside your home directory. ` +
`Only load themes from trusted sources.`,
);
@@ -259,14 +260,14 @@ class ThemeManager {
const validation = validateCustomTheme(customThemeConfig);
if (!validation.isValid) {
console.warn(
debugLogger.warn(
`Invalid custom theme from file "${themePath}": ${validation.error}`,
);
return undefined;
}
if (validation.warning) {
console.warn(`Theme from "${themePath}": ${validation.warning}`);
debugLogger.warn(`Theme from "${themePath}": ${validation.warning}`);
}
// 4. Create and cache the theme.
@@ -286,7 +287,10 @@ class ThemeManager {
if (
!(error instanceof Error && 'code' in error && error.code === 'ENOENT')
) {
console.warn(`Could not load theme from file "${themePath}":`, error);
debugLogger.warn(
`Could not load theme from file "${themePath}":`,
error,
);
}
return undefined;
}
+2 -1
View File
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { debugLogger } from '@google/gemini-cli-core';
import type { SpawnOptions } from 'node:child_process';
import { spawn } from 'node:child_process';
@@ -165,7 +166,7 @@ export const getUrlOpenCommand = (): string => {
default:
// Default to xdg-open, which appears to be supported for the less popular operating systems.
openCmd = 'xdg-open';
console.warn(
debugLogger.warn(
`Unknown platform: ${process.platform}. Attempting to open URLs with: ${openCmd}.`,
);
break;
+3 -2
View File
@@ -30,6 +30,7 @@ import { exec } from 'node:child_process';
import { promisify } from 'node:util';
import { isKittyProtocolEnabled } from './kittyProtocolDetector.js';
import { VSCODE_SHIFT_ENTER_SEQUENCE } from './platformConstants.js';
import { debugLogger } from '@google/gemini-cli-core';
const execAsync = promisify(exec);
@@ -88,7 +89,7 @@ async function detectTerminal(): Promise<SupportedTerminal | null> {
return 'vscode';
} catch (error) {
// Continue detection even if process check fails
console.debug('Parent process detection failed:', error);
debugLogger.debug('Parent process detection failed:', error);
}
}
@@ -103,7 +104,7 @@ async function backupFile(filePath: string): Promise<void> {
await fs.copyFile(filePath, backupPath);
} catch (error) {
// Log backup errors but continue with operation
console.warn(`Failed to create backup of ${filePath}:`, error);
debugLogger.warn(`Failed to create backup of ${filePath}:`, error);
}
}
+2 -1
View File
@@ -9,6 +9,7 @@ import updateNotifier from 'update-notifier';
import semver from 'semver';
import { getPackageJson } from '../../utils/package.js';
import type { LoadedSettings } from '../../config/settings.js';
import { debugLogger } from '@google/gemini-cli-core';
export const FETCH_TIMEOUT_MS = 2000;
@@ -101,7 +102,7 @@ export async function checkForUpdates(
return null;
} catch (e) {
console.warn('Failed to check for updates: ' + e);
debugLogger.warn('Failed to check for updates: ' + e);
return null;
}
}