Files
claude-task-master/mcp-server/src/logger.js
Eyal Toledano 4a9f6cd5f5 refactor: Standardize configuration and environment variable access
This commit centralizes configuration and environment variable access across various modules by consistently utilizing getters from scripts/modules/config-manager.js. This replaces direct access to process.env and the global CONFIG object, leading to improved consistency, maintainability, testability, and better handling of session-specific configurations within the MCP context.

Key changes include:

- Centralized Getters: Replaced numerous instances of process.env.* and CONFIG.* with corresponding getter functions (e.g., getLogLevel, getMainModelId, getResearchMaxTokens, getMainTemperature, isApiKeySet, getDebugFlag, getDefaultSubtasks).

- Session Awareness: Ensured that the session object is passed to config getters where necessary, particularly within AI service calls (ai-services.js, add-task.js) and error handling (ai-services.js), allowing for session-specific environment overrides.

- API Key Checks: Standardized API key availability checks using isApiKeySet() instead of directly checking process.env.* (e.g., for Perplexity in commands.js and ai-services.js).

- Client Instantiation Cleanup: Removed now-redundant/obsolete local client instantiation functions (getAnthropicClient, getPerplexityClient) from ai-services.js and the global Anthropic client initialization from dependency-manager.js. Client creation should now rely on the config manager and factory patterns.

- Consistent Debug Flag Usage: Standardized calls to getDebugFlag() in commands.js, removing potentially unnecessary null arguments.

- Accurate Progress Calculation: Updated AI stream progress reporting (ai-services.js, add-task.js) to use getMainMaxTokens(session) for more accurate calculations.

- Minor Cleanup: Removed unused  import from scripts/modules/commands.js.

Specific module updates:

- :

  - Uses getLogLevel() instead of process.env.LOG_LEVEL.

- :

  - Replaced direct env/config access for model IDs, tokens, temperature, API keys, and default subtasks with appropriate getters.

  - Passed session to handleClaudeError.

  - Removed local getPerplexityClient and getAnthropicClient functions.

  - Updated progress calculations to use getMainMaxTokens(session).

- :

  - Uses isApiKeySet('perplexity') for API key checks.

  - Uses getDebugFlag() consistently for debug checks.

  - Removed unused  import.

- :

  - Removed global Anthropic client initialization.

- :

  - Uses config getters (getResearch..., getMain...) for Perplexity and Claude API call parameters, preserving customEnv override logic.

This refactoring also resolves a potential SyntaxError: Identifier 'getPerplexityClient' has already been declared by removing the duplicated/obsolete function definition previously present in ai-services.js.
2025-04-21 21:30:12 -04:00

110 lines
2.9 KiB
JavaScript

import chalk from 'chalk';
import { isSilentMode } from '../../scripts/modules/utils.js';
import { getLogLevel } from '../../scripts/modules/config-manager.js';
// Define log levels
const LOG_LEVELS = {
debug: 0,
info: 1,
warn: 2,
error: 3,
success: 4
};
// Get log level from config manager or default to info
const LOG_LEVEL = LOG_LEVELS[getLogLevel().toLowerCase()] ?? LOG_LEVELS.info;
/**
* Logs a message with the specified level
* @param {string} level - The log level (debug, info, warn, error, success)
* @param {...any} args - Arguments to log
*/
function log(level, ...args) {
// Skip logging if silent mode is enabled
if (isSilentMode()) {
return;
}
// Use text prefixes instead of emojis
const prefixes = {
debug: chalk.gray('[DEBUG]'),
info: chalk.blue('[INFO]'),
warn: chalk.yellow('[WARN]'),
error: chalk.red('[ERROR]'),
success: chalk.green('[SUCCESS]')
};
if (LOG_LEVELS[level] !== undefined && LOG_LEVELS[level] >= LOG_LEVEL) {
const prefix = prefixes[level] || '';
let coloredArgs = args;
try {
switch (level) {
case 'error':
coloredArgs = args.map((arg) =>
typeof arg === 'string' ? chalk.red(arg) : arg
);
break;
case 'warn':
coloredArgs = args.map((arg) =>
typeof arg === 'string' ? chalk.yellow(arg) : arg
);
break;
case 'success':
coloredArgs = args.map((arg) =>
typeof arg === 'string' ? chalk.green(arg) : arg
);
break;
case 'info':
coloredArgs = args.map((arg) =>
typeof arg === 'string' ? chalk.blue(arg) : arg
);
break;
case 'debug':
coloredArgs = args.map((arg) =>
typeof arg === 'string' ? chalk.gray(arg) : arg
);
break;
// default: use original args (no color)
}
} catch (colorError) {
// Fallback if chalk fails on an argument
// Use console.error here for internal logger errors, separate from normal logging
console.error('Internal Logger Error applying chalk color:', colorError);
coloredArgs = args;
}
// Revert to console.log - FastMCP's context logger (context.log)
// is responsible for directing logs correctly (e.g., to stderr)
// during tool execution without upsetting the client connection.
// Logs outside of tool execution (like startup) will go to stdout.
console.log(prefix, ...coloredArgs);
}
}
/**
* Create a logger object with methods for different log levels
* @returns {Object} Logger object with info, error, debug, warn, and success methods
*/
export function createLogger() {
const createLogMethod =
(level) =>
(...args) =>
log(level, ...args);
return {
debug: createLogMethod('debug'),
info: createLogMethod('info'),
warn: createLogMethod('warn'),
error: createLogMethod('error'),
success: createLogMethod('success'),
log: log // Also expose the raw log function
};
}
// Export a default logger instance
const logger = createLogger();
export default logger;
export { log, LOG_LEVELS };