Skip to content

An AI-powered search engine with a generative UI

feat: make performance logging configurable via env variable

Yoshiki Miura71de93534132
diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts
index 462451e1..a1465f3e 100644
--- a/app/api/chat/route.ts
+++ b/app/api/chat/route.ts
@@ -1,6 +1,7 @@
import { cookies } from 'next/headers'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import { perfLog, perfTime } from '@/lib/utils/perf-logging'
import { resetAllCounters } from '@/lib/utils/perf-tracking'
import { createChatStreamResponse } from '@/lib/streaming/create-chat-stream-response'
import { Model } from '@/lib/types/models'
@@ -26,7 +27,7 @@ export async function POST(req: Request) {
const body = await req.json()
const { message, chatId, trigger, messageId, isNewChat } = body
- console.log(`[PERF] API Route - Start: chatId=${chatId}, trigger=${trigger}, isNewChat=${isNewChat}`)
+ perfLog(`API Route - Start: chatId=${chatId}, trigger=${trigger}, isNewChat=${isNewChat}`)
// Handle different triggers
if (trigger === 'regenerate-assistant-message') {
@@ -50,7 +51,7 @@ export async function POST(req: Request) {
const authStart = performance.now()
const userId = await getCurrentUserId()
- console.log(`[PERF] Auth completed: ${(performance.now() - authStart).toFixed(2)}ms`)
+ perfTime('Auth completed', authStart)
if (isSharePage) {
return new Response('Chat API is not available on share pages', {
@@ -103,13 +104,11 @@ export async function POST(req: Request) {
})
const totalTime = performance.now() - startTime
- console.log(`[PERF] Total API route time: ${totalTime.toFixed(2)}ms`)
-
- // Print summary
- console.log(`[PERF] === Summary ===`)
- console.log(`[PERF] Chat Type: ${isNewChat ? 'NEW' : 'EXISTING'}`)
- console.log(`[PERF] Total Time: ${totalTime.toFixed(2)}ms`)
- console.log(`[PERF] ================`)
+ perfLog(`Total API route time: ${totalTime.toFixed(2)}ms`)
+ perfLog(`=== Summary ===`)
+ perfLog(`Chat Type: ${isNewChat ? 'NEW' : 'EXISTING'}`)
+ perfLog(`Total Time: ${totalTime.toFixed(2)}ms`)
+ perfLog(`================`)
return response
} catch (error) {
diff --git a/lib/auth/get-current-user.ts b/lib/auth/get-current-user.ts
index d897f876..78573247 100644
--- a/lib/auth/get-current-user.ts
+++ b/lib/auth/get-current-user.ts
@@ -1,4 +1,5 @@
import { createClient } from '@/lib/supabase/server'
+import { perfLog } from '@/lib/utils/perf-logging'
import { incrementAuthCallCount } from '@/lib/utils/perf-tracking'
export async function getCurrentUser() {
@@ -16,7 +17,7 @@ export async function getCurrentUser() {
export async function getCurrentUserId() {
const count = incrementAuthCallCount()
- console.log(`[PERF] getCurrentUserId called - count: ${count}`)
+ perfLog(`getCurrentUserId called - count: ${count}`)
const user = await getCurrentUser()
return user?.id
}
diff --git a/lib/db/actions.ts b/lib/db/actions.ts
index ab863e4a..f7207e79 100644
--- a/lib/db/actions.ts
+++ b/lib/db/actions.ts
@@ -13,6 +13,7 @@ import {
import type { Chat, Message } from './schema'
import { chats, generateId, messages, parts } from './schema'
import { db } from '.'
+import { perfLog, perfTime } from '@/lib/utils/perf-logging'
import { incrementDbOperationCount } from '@/lib/utils/perf-tracking'
/**
@@ -78,7 +79,7 @@ export async function upsertMessage(
message: PersistableUIMessage & { chatId: string }
): Promise<Message> {
const count = incrementDbOperationCount()
- console.log(`[PERF] DB - upsertMessage called - count: ${count}`)
+ perfLog(`DB - upsertMessage called - count: ${count}`)
const result = await db.transaction(async tx => {
// 1. Insert or update the message
const messageData = mapUIMessageToDBMessage(message)
@@ -135,7 +136,7 @@ export async function loadChatWithMessages(
userId?: string
): Promise<(Chat & { messages: UIMessage[] }) | null> {
const count = incrementDbOperationCount()
- console.log(`[PERF] DB - loadChatWithMessages called - count: ${count}`)
+ perfLog(`DB - loadChatWithMessages called - count: ${count}`)
// Don't check cache yet - need to verify permissions first
// Get chat and messages in parallel
@@ -357,7 +358,7 @@ export async function createChatWithFirstMessageTransaction({
userId: string
message: PersistableUIMessage
}): Promise<{ chat: Chat; message: Message }> {
- console.log(`[PERF] DB - createChatWithFirstMessageTransaction start`)
+ perfLog(`DB - createChatWithFirstMessageTransaction start`)
const dbStart = performance.now()
return await db.transaction(async tx => {
// 1. Create chat
@@ -384,7 +385,7 @@ export async function createChatWithFirstMessageTransaction({
}
}
- console.log(`[PERF] DB - createChatWithFirstMessageTransaction completed: ${(performance.now() - dbStart).toFixed(2)}ms`)
+ perfTime('DB - createChatWithFirstMessageTransaction completed', dbStart)
return { chat, message: savedMessage }
})
}
diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.ts
index 6609e73e..59fa69d9 100644
--- a/lib/streaming/create-chat-stream-response.ts
+++ b/lib/streaming/create-chat-stream-response.ts
@@ -14,6 +14,7 @@ import { isTracingEnabled } from '@/lib/utils/telemetry'
import { loadChat } from '../actions/chat'
import { generateChatTitle } from '../agents/title-generator'
+import { perfLog, perfTime } from '../utils/perf-logging'
import {
getMaxAllowedTokens,
shouldTruncateMessages,
@@ -51,7 +52,7 @@ export async function createChatStreamResponse(
const loadChatStart = performance.now()
// Fetch chat data for authorization check and cache it
initialChat = await loadChat(chatId, userId)
- console.log(`[PERF] loadChat completed: ${(performance.now() - loadChatStart).toFixed(2)}ms`)
+ perfTime('loadChat completed', loadChatStart)
// Authorization check: if chat exists, it must belong to the user
if (initialChat && initialChat.userId !== userId) {
@@ -61,7 +62,7 @@ export async function createChatStreamResponse(
})
}
} else {
- console.log(`[PERF] loadChat skipped for new chat`)
+ perfLog('loadChat skipped for new chat')
}
// Create parent trace ID for grouping all operations
diff --git a/lib/streaming/helpers/handle-stream-finish.ts b/lib/streaming/helpers/handle-stream-finish.ts
index dba636ed..e07e635a 100644
--- a/lib/streaming/helpers/handle-stream-finish.ts
+++ b/lib/streaming/helpers/handle-stream-finish.ts
@@ -5,6 +5,7 @@ import { generateRelatedQuestions } from '@/lib/agents/generate-related-question
import { updateChatTitle } from '@/lib/db/actions'
import { generateId } from '@/lib/db/schema'
import { hasToolCalls } from '@/lib/utils/message-utils'
+import { perfTime } from '@/lib/utils/perf-logging'
import { retryDatabaseOperation } from '@/lib/utils/retry'
import type { StreamContext } from './types'
@@ -80,7 +81,7 @@ export async function handleStreamFinish(
const saveStart = performance.now()
upsertMessage(chatId, responseMessage, userId)
.then(() => {
- console.log(`[PERF] upsertMessage (AI response) completed: ${(performance.now() - saveStart).toFixed(2)}ms`)
+ perfTime('upsertMessage (AI response) completed', saveStart)
})
.catch(async error => {
console.error('Error saving message:', error)
diff --git a/lib/streaming/helpers/prepare-messages.ts b/lib/streaming/helpers/prepare-messages.ts
index 990dbccc..d2f2d698 100644
--- a/lib/streaming/helpers/prepare-messages.ts
+++ b/lib/streaming/helpers/prepare-messages.ts
@@ -7,6 +7,7 @@ import {
upsertMessage
} from '@/lib/actions/chat'
import { generateId } from '@/lib/db/schema'
+import { perfLog, perfTime } from '@/lib/utils/perf-logging'
import type { StreamContext } from './types'
@@ -18,7 +19,7 @@ export async function prepareMessages(
): Promise<UIMessage[]> {
const { chatId, userId, trigger, messageId, initialChat, isNewChat } = context
const startTime = performance.now()
- console.log(`[PERF] prepareMessages - Start: trigger=${trigger}, isNewChat=${isNewChat}`)
+ perfLog(`prepareMessages - Start: trigger=${trigger}, isNewChat=${isNewChat}`)
if (trigger === 'regenerate-assistant-message' && messageId) {
// Handle regeneration - use initialChat if available to avoid DB call
@@ -87,8 +88,8 @@ export async function prepareMessages(
const createStart = performance.now()
const { createChatWithFirstMessage } = await import('@/lib/actions/chat')
await createChatWithFirstMessage(chatId, messageWithId, userId, DEFAULT_CHAT_TITLE)
- console.log(`[PERF] createChatWithFirstMessage completed: ${(performance.now() - createStart).toFixed(2)}ms`)
- console.log(`[PERF] prepareMessages - Total: ${(performance.now() - startTime).toFixed(2)}ms`)
+ perfTime('createChatWithFirstMessage completed', createStart)
+ perfTime('prepareMessages - Total', startTime)
return [messageWithId]
}
@@ -96,24 +97,24 @@ export async function prepareMessages(
if (!initialChat) {
const createStart = performance.now()
await createChat(chatId, DEFAULT_CHAT_TITLE, userId)
- console.log(`[PERF] createChat completed: ${(performance.now() - createStart).toFixed(2)}ms`)
+ perfTime('createChat completed', createStart)
}
const upsertStart = performance.now()
await upsertMessage(chatId, messageWithId, userId)
- console.log(`[PERF] upsertMessage completed: ${(performance.now() - upsertStart).toFixed(2)}ms`)
+ perfTime('upsertMessage completed', upsertStart)
// If we have initialChat, append the new message instead of fetching all messages
if (initialChat && initialChat.messages) {
- console.log(`[PERF] prepareMessages - Total: ${(performance.now() - startTime).toFixed(2)}ms (using cached chat)`)
+ perfTime('prepareMessages - Total (using cached chat)', startTime)
return [...initialChat.messages, messageWithId]
}
// Fallback to fetching if no initialChat
const loadStart = performance.now()
const updatedChat = await loadChat(chatId, userId)
- console.log(`[PERF] loadChat (fallback) completed: ${(performance.now() - loadStart).toFixed(2)}ms`)
- console.log(`[PERF] prepareMessages - Total: ${(performance.now() - startTime).toFixed(2)}ms`)
+ perfTime('loadChat (fallback) completed', loadStart)
+ perfTime('prepareMessages - Total', startTime)
return updatedChat?.messages || [messageWithId]
}
}
diff --git a/lib/utils/perf-logging.ts b/lib/utils/perf-logging.ts
new file mode 100644
index 00000000..4fd83b02
--- /dev/null
+++ b/lib/utils/perf-logging.ts
@@ -0,0 +1,15 @@
+// Performance logging utilities
+
+const isPerfLoggingEnabled = process.env.ENABLE_PERF_LOGGING === 'true'
+
+export function perfLog(message: string) {
+ if (isPerfLoggingEnabled) {
+ console.log(`[PERF] ${message}`)
+ }
+}
+
+export function perfTime(label: string, startTime: number) {
+ if (isPerfLoggingEnabled) {
+ console.log(`[PERF] ${label}: ${(performance.now() - startTime).toFixed(2)}ms`)
+ }
+}
\ No newline at end of file