refactor(logging): 将console替换为logger以统一日志管理

This commit is contained in:
icarus 2025-08-28 14:52:59 +08:00
parent a12d627b65
commit 5f096ecf8c
8 changed files with 37 additions and 32 deletions

View File

@ -435,7 +435,7 @@ export default class ModernAiProvider {
const result = await this.modernGenerateImage(params) const result = await this.modernGenerateImage(params)
return result return result
} catch (error) { } catch (error) {
console.warn('Modern AI SDK generateImage failed, falling back to legacy:', error) logger.warn('Modern AI SDK generateImage failed, falling back to legacy:', error as Error)
// fallback 到传统实现 // fallback 到传统实现
return this.legacyProvider.generateImage(params) return this.legacyProvider.generateImage(params)
} }

View File

@ -62,7 +62,7 @@ export class ApiClientFactory {
instance = new GeminiAPIClient(provider) as BaseApiClient instance = new GeminiAPIClient(provider) as BaseApiClient
break break
case 'vertexai': case 'vertexai':
console.log(`[ApiClientFactory] Creating VertexAPIClient for provider: ${provider.id}`) logger.debug(`Creating VertexAPIClient for provider: ${provider.id}`)
// 检查 VertexAI 配置 // 检查 VertexAI 配置
if (!isVertexAIConfigured()) { if (!isVertexAIConfigured()) {
throw new Error( throw new Error(

View File

@ -3,9 +3,12 @@ import {
LanguageModelV2Middleware, LanguageModelV2Middleware,
simulateStreamingMiddleware simulateStreamingMiddleware
} from '@cherrystudio/ai-core' } from '@cherrystudio/ai-core'
import { loggerService } from '@logger'
import type { MCPTool, Model, Provider } from '@renderer/types' import type { MCPTool, Model, Provider } from '@renderer/types'
import type { Chunk } from '@renderer/types/chunk' import type { Chunk } from '@renderer/types/chunk'
const logger = loggerService.withContext('AiSdkMiddlewareBuilder')
/** /**
* AI SDK * AI SDK
*/ */
@ -57,7 +60,7 @@ export class AiSdkMiddlewareBuilder {
if (index !== -1) { if (index !== -1) {
this.middlewares.splice(index + 1, 0, middleware) this.middlewares.splice(index + 1, 0, middleware)
} else { } else {
console.warn(`AiSdkMiddlewareBuilder: 未找到名为 '${targetName}' 的中间件,无法插入`) logger.warn(`AiSdkMiddlewareBuilder: Middleware named '${targetName}' not found, cannot insert`)
} }
return this return this
} }
@ -132,7 +135,7 @@ export function buildAiSdkMiddlewares(config: AiSdkMiddlewareConfig): LanguageMo
}) })
} }
console.log('builder.build()', builder.buildNamed()) logger.info('builder.build()', builder.buildNamed())
return builder.build() return builder.build()
} }

View File

@ -1,5 +1,6 @@
import { AiPlugin } from '@cherrystudio/ai-core' import { AiPlugin } from '@cherrystudio/ai-core'
import { createPromptToolUsePlugin, webSearchPlugin } from '@cherrystudio/ai-core/built-in/plugins' import { createPromptToolUsePlugin, webSearchPlugin } from '@cherrystudio/ai-core/built-in/plugins'
import { loggerService } from '@logger'
import { getEnableDeveloperMode } from '@renderer/hooks/useSettings' import { getEnableDeveloperMode } from '@renderer/hooks/useSettings'
import { Assistant } from '@renderer/types' import { Assistant } from '@renderer/types'
@ -8,6 +9,7 @@ import reasoningTimePlugin from './reasoningTimePlugin'
import { searchOrchestrationPlugin } from './searchOrchestrationPlugin' import { searchOrchestrationPlugin } from './searchOrchestrationPlugin'
import { createTelemetryPlugin } from './telemetryPlugin' import { createTelemetryPlugin } from './telemetryPlugin'
const logger = loggerService.withContext('PluginBuilder')
/** /**
* *
*/ */
@ -70,8 +72,8 @@ export function buildPlugins(
// if (!middlewareConfig.enableTool && middlewareConfig.mcpTools && middlewareConfig.mcpTools.length > 0) { // if (!middlewareConfig.enableTool && middlewareConfig.mcpTools && middlewareConfig.mcpTools.length > 0) {
// plugins.push(createNativeToolUsePlugin()) // plugins.push(createNativeToolUsePlugin())
// } // }
console.log( logger.info(
'最终插件列表:', 'Final plugin list:',
plugins.map((p) => p.name) plugins.map((p) => p.name)
) )
return plugins return plugins

View File

@ -119,7 +119,7 @@ async function analyzeSearchIntent(
const provider = getProviderByModel(model) const provider = getProviderByModel(model)
if (!provider || isEmpty(provider.apiKey)) { if (!provider || isEmpty(provider.apiKey)) {
console.error('Provider not found or missing API key') logger.error('Provider not found or missing API key')
return getFallbackResult() return getFallbackResult()
} }
// console.log('formattedPrompt', schema) // console.log('formattedPrompt', schema)
@ -198,9 +198,9 @@ async function storeConversationMemory(
content: getMessageContent(msg) || '' content: getMessageContent(msg) || ''
})) }))
.filter((msg) => msg.content.trim().length > 0) .filter((msg) => msg.content.trim().length > 0)
console.log('conversationMessages', conversationMessages) logger.debug('conversationMessages', conversationMessages)
if (conversationMessages.length < 2) { if (conversationMessages.length < 2) {
console.log('Need at least a user message and assistant response for memory processing') logger.info('Need at least a user message and assistant response for memory processing')
return return
} }
@ -214,26 +214,26 @@ async function storeConversationMemory(
context.requestId context.requestId
) )
console.log('Processing conversation memory...', { messageCount: conversationMessages.length }) logger.info('Processing conversation memory...', { messageCount: conversationMessages.length })
// 后台处理对话记忆(不阻塞 UI // 后台处理对话记忆(不阻塞 UI
const memoryProcessor = new MemoryProcessor() const memoryProcessor = new MemoryProcessor()
memoryProcessor memoryProcessor
.processConversation(conversationMessages, processorConfig) .processConversation(conversationMessages, processorConfig)
.then((result) => { .then((result) => {
console.log('Memory processing completed:', result) logger.info('Memory processing completed:', result)
if (result.facts?.length > 0) { if (result.facts?.length > 0) {
console.log('Extracted facts from conversation:', result.facts) logger.info('Extracted facts from conversation:', result.facts)
console.log('Memory operations performed:', result.operations) logger.info('Memory operations performed:', result.operations)
} else { } else {
console.log('No facts extracted from conversation') logger.info('No facts extracted from conversation')
} }
}) })
.catch((error) => { .catch((error) => {
console.error('Background memory processing failed:', error) logger.error('Background memory processing failed:', error as Error)
}) })
} catch (error) { } catch (error) {
console.error('Error in conversation memory processing:', error) logger.error('Error in conversation memory processing:', error as Error)
// 不抛出错误,避免影响主流程 // 不抛出错误,避免影响主流程
} }
} }
@ -302,11 +302,11 @@ export const searchOrchestrationPlugin = (assistant: Assistant, topicId: string)
if (analysisResult) { if (analysisResult) {
intentAnalysisResults[context.requestId] = analysisResult intentAnalysisResults[context.requestId] = analysisResult
// console.log('🧠 [SearchOrchestration] Intent analysis completed:', analysisResult) // logger.info('🧠 Intent analysis completed:', analysisResult)
} }
} }
} catch (error) { } catch (error) {
console.error('🧠 [SearchOrchestration] Intent analysis failed:', error) logger.error('🧠 Intent analysis failed:', error as Error)
// 不抛出错误,让流程继续 // 不抛出错误,让流程继续
} }
}, },
@ -316,12 +316,12 @@ export const searchOrchestrationPlugin = (assistant: Assistant, topicId: string)
*/ */
transformParams: async (params: any, context: AiRequestContext) => { transformParams: async (params: any, context: AiRequestContext) => {
if (context.isAnalyzing) return params if (context.isAnalyzing) return params
// console.log('🔧 [SearchOrchestration] Configuring tools based on intent...', context.requestId) // logger.info('🔧 Configuring tools based on intent...', context.requestId)
try { try {
const analysisResult = intentAnalysisResults[context.requestId] const analysisResult = intentAnalysisResults[context.requestId]
// if (!analysisResult || !assistant) { // if (!analysisResult || !assistant) {
// console.log('🔧 [SearchOrchestration] No analysis result or assistant, skipping tool configuration') // logger.info('🔧 No analysis result or assistant, skipping tool configuration')
// return params // return params
// } // }
@ -336,7 +336,7 @@ export const searchOrchestrationPlugin = (assistant: Assistant, topicId: string)
if (needsSearch) { if (needsSearch) {
// onChunk({ type: ChunkType.EXTERNEL_TOOL_IN_PROGRESS }) // onChunk({ type: ChunkType.EXTERNEL_TOOL_IN_PROGRESS })
// console.log('🌐 [SearchOrchestration] Adding web search tool with pre-extracted keywords') // logger.info('🌐 Adding web search tool with pre-extracted keywords')
params.tools['builtin_web_search'] = webSearchToolWithPreExtractedKeywords( params.tools['builtin_web_search'] = webSearchToolWithPreExtractedKeywords(
assistant.webSearchProviderId, assistant.webSearchProviderId,
analysisResult.websearch, analysisResult.websearch,
@ -358,7 +358,7 @@ export const searchOrchestrationPlugin = (assistant: Assistant, topicId: string)
question: [getMessageContent(userMessage) || 'search'], question: [getMessageContent(userMessage) || 'search'],
rewrite: getMessageContent(userMessage) || 'search' rewrite: getMessageContent(userMessage) || 'search'
} }
// console.log('📚 [SearchOrchestration] Adding knowledge search tool (force mode)') // logger.info('📚 Adding knowledge search tool (force mode)')
params.tools['builtin_knowledge_search'] = knowledgeSearchTool( params.tools['builtin_knowledge_search'] = knowledgeSearchTool(
assistant, assistant,
fallbackKeywords, fallbackKeywords,
@ -374,7 +374,7 @@ export const searchOrchestrationPlugin = (assistant: Assistant, topicId: string)
analysisResult.knowledge.question[0] !== 'not_needed' analysisResult.knowledge.question[0] !== 'not_needed'
if (needsKnowledgeSearch && analysisResult.knowledge) { if (needsKnowledgeSearch && analysisResult.knowledge) {
// console.log('📚 [SearchOrchestration] Adding knowledge search tool (intent-based)') // logger.info('📚 Adding knowledge search tool (intent-based)')
const userMessage = userMessages[context.requestId] const userMessage = userMessages[context.requestId]
params.tools['builtin_knowledge_search'] = knowledgeSearchTool( params.tools['builtin_knowledge_search'] = knowledgeSearchTool(
assistant, assistant,
@ -389,14 +389,14 @@ export const searchOrchestrationPlugin = (assistant: Assistant, topicId: string)
// 🧠 记忆搜索工具配置 // 🧠 记忆搜索工具配置
const globalMemoryEnabled = selectGlobalMemoryEnabled(store.getState()) const globalMemoryEnabled = selectGlobalMemoryEnabled(store.getState())
if (globalMemoryEnabled && assistant.enableMemory) { if (globalMemoryEnabled && assistant.enableMemory) {
// console.log('🧠 [SearchOrchestration] Adding memory search tool') // logger.info('🧠 Adding memory search tool')
params.tools['builtin_memory_search'] = memorySearchTool() params.tools['builtin_memory_search'] = memorySearchTool()
} }
// console.log('🔧 [SearchOrchestration] Tools configured:', Object.keys(params.tools)) // logger.info('🔧 Tools configured:', Object.keys(params.tools))
return params return params
} catch (error) { } catch (error) {
console.error('🔧 [SearchOrchestration] Tool configuration failed:', error) logger.error('🔧 Tool configuration failed:', error as Error)
return params return params
} }
}, },
@ -407,8 +407,8 @@ export const searchOrchestrationPlugin = (assistant: Assistant, topicId: string)
onRequestEnd: async (context: AiRequestContext) => { onRequestEnd: async (context: AiRequestContext) => {
// context.isAnalyzing = false // context.isAnalyzing = false
// console.log('context.isAnalyzing', context, result) // logger.info('context.isAnalyzing', context, result)
// console.log('💾 [SearchOrchestration] Starting memory storage...', context.requestId) // logger.info('💾 Starting memory storage...', context.requestId)
if (context.isAnalyzing) return if (context.isAnalyzing) return
try { try {
const messages = context.originalParams.messages const messages = context.originalParams.messages
@ -421,7 +421,7 @@ export const searchOrchestrationPlugin = (assistant: Assistant, topicId: string)
delete intentAnalysisResults[context.requestId] delete intentAnalysisResults[context.requestId]
delete userMessages[context.requestId] delete userMessages[context.requestId]
} catch (error) { } catch (error) {
console.error('💾 [SearchOrchestration] Memory storage failed:', error) logger.error('💾 Memory storage failed:', error as Error)
// 不抛出错误,避免影响主流程 // 不抛出错误,避免影响主流程
} }
} }

View File

@ -150,7 +150,7 @@ class WebSearchService {
*/ */
public getWebSearchProvider(providerId?: string): WebSearchProvider | undefined { public getWebSearchProvider(providerId?: string): WebSearchProvider | undefined {
const { providers } = this.getWebSearchState() const { providers } = this.getWebSearchState()
console.log('providers', providers) logger.debug('providers', providers)
const provider = providers.find((provider) => provider.id === providerId) const provider = providers.find((provider) => provider.id === providerId)
return provider return provider

View File

@ -105,7 +105,7 @@ export class BlockManager {
* *
*/ */
async handleBlockTransition(newBlock: MessageBlock, newBlockType: MessageBlockType) { async handleBlockTransition(newBlock: MessageBlock, newBlockType: MessageBlockType) {
console.log('handleBlockTransition', newBlock, newBlockType) logger.debug('handleBlockTransition', { newBlock, newBlockType })
this._lastBlockType = newBlockType this._lastBlockType = newBlockType
this._activeBlockInfo = { id: newBlock.id, type: newBlockType } // 设置新的活跃块信息 this._activeBlockInfo = { id: newBlock.id, type: newBlockType } // 设置新的活跃块信息

View File

@ -23,7 +23,7 @@ export const createToolCallbacks = (deps: ToolCallbacksDependencies) => {
return { return {
onToolCallPending: (toolResponse: MCPToolResponse) => { onToolCallPending: (toolResponse: MCPToolResponse) => {
console.log('onToolCallPending', toolResponse) logger.debug('onToolCallPending', toolResponse)
if (blockManager.hasInitialPlaceholder) { if (blockManager.hasInitialPlaceholder) {
const changes = { const changes = {