Unverified Commit f4b40dcd authored by Ben Gubler's avatar Ben Gubler Committed by GitHub

refactor: remove ClientFileLogger, consolidate file logging into handleLog (#92329)

## Background: three sources of file log entries

Browser `console.*` calls in Next.js dev mode are forwarded to the
server over a WebSocket. Before this PR, three independent mechanisms
wrote to the `.next/logs/next-development.log` file:

1. **`ClientFileLogger`** (client → `client-file-logs` WS event →
`handleClientFileLogs`) — a class in `forward-logs.ts` that intercepted
every `console.*` call unconditionally, serialized args into
message-only strings (no stack traces, no source mapping), and sent them
to the server over a separate `client-file-logs` WebSocket event. The
server's `handleClientFileLogs` wrote them directly to the file logger
as `Browser` entries.

2. **`handleLog` direct file writes** (client → `browser-logs` WS event
→ `handleLog` → `fileLogger`) — the primary path. The browser's patched
console methods serialize args into `ClientLogEntry` objects, batch
them, and send them as `browser-logs` WebSocket events. On the server,
`handleLog` in `receive-logs.ts` deserializes the args, source-maps
stack traces, and forwards to the terminal. As a side effect, it also
wrote directly to the file logger.

3. **`console-file.tsx` interception** (server-side `console.*` →
`fileLogger.logServer`) — a server-side environment extension that
patches the server process's own `console.*` methods. When `handleLog`
calls `forwardConsole.error()` to print browser logs to the terminal,
this interception captures that output and writes it as a `Server`
entry. The `[browser]` text visible in these entries' messages is the
terminal prefix leaking into the file log.

## Problems with the old system

### Duplicate entries

On the client side, `createLogEntry` gated the `browser-logs` send
behind `isTerminalLoggingEnabled`:

```javascript
if (!isTerminalLoggingEnabled) {
  return  // skip browser-logs WebSocket send
}
```

But `clientFileLogger.log()` was called **before** this check,
unconditionally. So `ClientFileLogger` always produced file log entries
regardless of config.

Meanwhile, `handleLog` was gated by `browserToTerminalConfig` in both
hot reloaders. Because `experimental.browserDebugInfoInTerminal`
defaults to `'warn'`, this gate was open by default — `handleLog` ran
for errors and warnings even in code without explicit
`logging.browserToTerminal` config, like this test. But `console.log`
was filtered out at the `'warn'` level, so only `ClientFileLogger` wrote
those.

The net effect: errors and warnings were written to the file by **both**
`ClientFileLogger` (message-only) and `handleLog` (with source-mapped
stacks), producing duplicates. `console.log` was written only by
`ClientFileLogger`.

### Mislabeled source

The direct file writes inside `handleLog` had a bug: the
`any-logged-error` and `formatted-error` code paths hardcoded
`fileLogger.logBrowser()` instead of checking `isServerLog`. The
`console` kind already checked `isServerLog` correctly. This
inconsistency meant that when a server-decorated error (one with the
`Symbol.for('NextjsError')` property set by `decorateServerError`) was
logged via `console.error(serverError)` in the browser, the `sourceType`
would be legitimately set to `'server'`, but the file log entry would
still be labeled `Browser`.

This bug didn't manifest in this test because the test calls
`console.error('string')` with no Error objects — `forwardErrorLog`
never finds an Error to call `getErrorSource` on, so `sourceType`
remains `undefined` and `isServerLog` is `false`. The hardcoded
`logBrowser` happened to produce the correct label by coincidence.

### The result

With the default config, a single `console.error('string')` in the
browser produced **three** file log entries:

1. `Browser ERROR` (message-only) — from `ClientFileLogger`
2. `Browser ERROR` (with stack) — from `handleLog`'s direct file write
(hardcoded `logBrowser`)
3. `Server ERROR` (with stack + `[browser]` prefix) — from
`console-file.tsx` intercepting `handleLog`'s `forwardConsole.error()`
terminal output

## What this PR does

**Removes `ClientFileLogger` and the `client-file-logs` channel
entirely.** File logging now happens via `handleLog`'s direct writes and
`console-file.tsx` interception.

**Decouples the client-side send from terminal logging.** The old
`createLogEntry` gated the `browser-logs` send on
`isTerminalLoggingEnabled`. The new code gates on `shouldForwardLogs`:

```javascript
const shouldForwardLogs = isTerminalLoggingEnabled || !!process.env.__NEXT_MCP_SERVER
```

This is the key mechanism that makes consolidation possible —
`browser-logs` events now fire when either terminal logging or the MCP
server (which controls file logging) is enabled, so `handleLog` always
receives the entries it needs.

**Decouples server-side file logging from terminal output.** `handleLog`
is no longer gated by `browserToTerminalConfig` at the hot-reloader
level — it always runs. Inside `handleLog`, terminal output and file
logging are controlled independently: `shouldShowEntry(entry, config)`
gates terminal output, `fileLogger.isEnabled()` gates file writes.

**Fixes the `isServerLog` labeling bug.** All entry kinds (`console`,
`any-logged-error`, `formatted-error`) now check `isServerLog` and call
`logServer()`/`logBrowser()` accordingly.

## Snapshot diff explanation

### Old snapshot (7 entries)

```
1. Browser LOG   — "Complex circular object: ..."        ← ClientFileLogger
2. Browser ERROR — "message"                             ← ClientFileLogger (message-only)
3. Browser WARN  — "message"                             ← ClientFileLogger (message-only)
4. Server ERROR  — "[browser] message + stack + loc"     ← console-file.tsx (intercepting forwardConsole.error)
5. Browser ERROR — "message + stack + loc"               ← handleLog any-logged-error (hardcoded logBrowser)
6. Server WARN   — "[browser] message + loc"             ← console-file.tsx (intercepting forwardConsole.warn)
7. Browser WARN  — "message"                             ← handleLog console kind (logBrowser, isServerLog=false)
```

### New snapshot (5 entries)

```
1. Browser LOG   — "Complex circular object: ..."        ← handleLog console kind (logBrowser)
2. Browser ERROR — "message + stack + loc"               ← handleLog any-logged-error (logBrowser)
3. Server ERROR  — "[browser] message + stack + loc"     ← console-file.tsx (intercepting forwardConsole.error)
4. Browser WARN  — "message"                             ← handleLog console kind (logBrowser)
5. Server WARN   — "[browser] message + loc"             ← console-file.tsx (intercepting forwardConsole.warn)
```

### What changed

With `ClientFileLogger` removed, each `console.*` call now produces one
`Browser` entry from `handleLog` instead of two (ClientFileLogger
message-only + handleLog with stack). Per call:

- **`console.log`**: old `#1` (ClientFileLogger) → new `#1` (handleLog).
Previously only `ClientFileLogger` wrote this — `handleLog` skipped it
because `log` level was below the `'warn'` terminal threshold. Now
`handleLog` writes file logs for all entry kinds before the `shouldShow`
check.
- **`console.error`**: old `#2` (ClientFileLogger duplicate) removed.
Old `#5` (handleLog) → new `#2`, now with cleaner formatting.
- **`console.warn`**: old `#3` (ClientFileLogger duplicate) removed. Old
`#7` (handleLog) → new `#4`.
- **`console-file.tsx` entries unchanged**: old `#4`/`#6` → new
`#3`/`#5`. These are artifacts of `console-file.tsx` intercepting the
server process's terminal output, not from `handleLog` directly.
parent e309a6ef
...@@ -8,121 +8,12 @@ import { ...@@ -8,121 +8,12 @@ import {
type LogMethod, type LogMethod,
patchConsoleMethod, patchConsoleMethod,
} from '../../shared/forward-logs-shared' } from '../../shared/forward-logs-shared'
import { import { preLogSerializationClone, logStringify } from './forward-logs-utils'
preLogSerializationClone,
logStringify,
safeStringifyWithDepth,
} from './forward-logs-utils'
import { getOwnerStack } from './errors/stitched-error' import { getOwnerStack } from './errors/stitched-error'
// Client-side file logger for browser logs
class ClientFileLogger {
private logEntries: Array<{
timestamp: string
level: string // log level
message: string // log message
}> = []
private formatTimestamp(): string {
const now = new Date()
const hours = now.getHours().toString().padStart(2, '0')
const minutes = now.getMinutes().toString().padStart(2, '0')
const seconds = now.getSeconds().toString().padStart(2, '0')
const milliseconds = now.getMilliseconds().toString().padStart(3, '0')
return `${hours}:${minutes}:${seconds}.${milliseconds}`
}
log(level: string, args: any[]): void {
if (isReactServerReplayedLog(args)) {
return
}
// Format the args into a message string
const message = args
.map((arg) => {
if (typeof arg === 'string') return arg
if (typeof arg === 'number' || typeof arg === 'boolean')
return String(arg)
if (arg === null) return 'null'
if (arg === undefined) return 'undefined'
// Handle DOM nodes - only log the tag name to avoid React proxied elements
if (arg instanceof Element) {
return `<${arg.tagName.toLowerCase()}>`
}
return safeStringifyWithDepth(arg)
})
.join(' ')
const logEntry = {
timestamp: this.formatTimestamp(),
level: level.toUpperCase(),
message,
}
this.logEntries.push(logEntry)
// Schedule flush when new log is added
scheduleLogFlush()
}
getLogs(): Array<{ timestamp: string; level: string; message: string }> {
return [...this.logEntries]
}
clear(): void {
this.logEntries = []
}
}
const clientFileLogger = new ClientFileLogger()
// Set up flush-based sending of client file logs
let logFlushTimeout: NodeJS.Timeout | null = null
let heartbeatInterval: NodeJS.Timeout | null = null
const scheduleLogFlush = () => {
if (logFlushTimeout) {
clearTimeout(logFlushTimeout)
}
logFlushTimeout = setTimeout(() => {
sendClientFileLogs()
logFlushTimeout = null
}, 100) // Send after 100ms (much faster with debouncing)
}
const cancelLogFlush = () => {
if (logFlushTimeout) {
clearTimeout(logFlushTimeout)
logFlushTimeout = null
}
}
const startHeartbeat = () => {
if (heartbeatInterval) return
heartbeatInterval = setInterval(() => {
if (logQueue.socket && logQueue.socket.readyState === WebSocket.OPEN) {
try {
// Send a ping to keep the connection alive
logQueue.socket.send(JSON.stringify({ event: 'ping' }))
} catch (error) {
// Connection might be closed, stop heartbeat
stopHeartbeat()
}
} else {
stopHeartbeat()
}
}, 5000) // Send ping every 5 seconds
}
const stopHeartbeat = () => {
if (heartbeatInterval) {
clearInterval(heartbeatInterval)
heartbeatInterval = null
}
}
const isTerminalLoggingEnabled = getIsTerminalLoggingEnabled() const isTerminalLoggingEnabled = getIsTerminalLoggingEnabled()
const shouldForwardLogs =
isTerminalLoggingEnabled || !!process.env.__NEXT_MCP_SERVER
const methods: Array<LogMethod> = [ const methods: Array<LogMethod> = [
'log', 'log',
...@@ -175,30 +66,22 @@ const serializeEntries = (entries: Array<ClientLogEntry>) => ...@@ -175,30 +66,22 @@ const serializeEntries = (entries: Array<ClientLogEntry>) =>
} }
}) })
// Function to send client file logs to server const flushBufferedEntries = (socket: WebSocket) => {
const sendClientFileLogs = () => { if (logQueue.entries.length === 0) {
if (!logQueue.socket || logQueue.socket.readyState !== WebSocket.OPEN) {
return
}
const logs = clientFileLogger.getLogs()
if (logs.length === 0) {
return return
} }
try { const payload = JSON.stringify({
const payload = JSON.stringify({ event: 'browser-logs',
event: 'client-file-logs', entries: serializeEntries(logQueue.entries),
logs: logs, router: logQueue.router,
}) // needed for source mapping, we just assign the sourceType from the last error for the whole batch
sourceType: logQueue.sourceType,
})
logQueue.socket.send(payload) socket.send(payload)
} catch (error) { logQueue.entries = []
console.error(error) logQueue.sourceType = undefined
} finally {
// Clear logs regardless of send success to prevent memory leaks
clientFileLogger.clear()
}
} }
// Combined state and public API // Combined state and public API
...@@ -238,20 +121,7 @@ export const logQueue: { ...@@ -238,20 +121,7 @@ export const logQueue: {
// just incase // just incase
try { try {
const payload = JSON.stringify({ flushBufferedEntries(socket)
event: 'browser-logs',
entries: serializeEntries(logQueue.entries),
router: logQueue.router,
// needed for source mapping, we just assign the sourceType from the last error for the whole batch
sourceType: logQueue.sourceType,
})
socket.send(payload)
logQueue.entries = []
logQueue.sourceType = undefined
// Also send client file logs
sendClientFileLogs()
} catch { } catch {
// error (make sure u don't infinite loop) // error (make sure u don't infinite loop)
/* noop */ /* noop */
...@@ -261,7 +131,7 @@ export const logQueue: { ...@@ -261,7 +131,7 @@ export const logQueue: {
onSocketReady: (socket: WebSocket) => { onSocketReady: (socket: WebSocket) => {
// When MCP or terminal logging is enabled, we enable the socket connection, // When MCP or terminal logging is enabled, we enable the socket connection,
// otherwise it will not proceed. // otherwise it will not proceed.
if (!isTerminalLoggingEnabled && !process.env.__NEXT_MCP_SERVER) { if (!shouldForwardLogs) {
return return
} }
if (socket.readyState !== WebSocket.OPEN) { if (socket.readyState !== WebSocket.OPEN) {
...@@ -273,35 +143,11 @@ export const logQueue: { ...@@ -273,35 +143,11 @@ export const logQueue: {
logQueue.cancelFlush?.() logQueue.cancelFlush?.()
logQueue.socket = socket logQueue.socket = socket
// Add socket event listeners to track connection state try {
socket.addEventListener('close', () => { flushBufferedEntries(socket)
cancelLogFlush() } catch {
stopHeartbeat() /** noop just incase */
})
// Only send terminal logs if enabled
if (isTerminalLoggingEnabled) {
try {
const payload = JSON.stringify({
event: 'browser-logs',
entries: serializeEntries(logQueue.entries),
router: logQueue.router,
sourceType: logQueue.sourceType,
})
socket.send(payload)
logQueue.entries = []
logQueue.sourceType = undefined
} catch {
/** noop just incase */
}
} }
// Always send client file logs when socket is ready
sendClientFileLogs()
// Start heartbeat to keep connection alive
startHeartbeat()
}, },
} }
...@@ -333,11 +179,7 @@ const createErrorArg = (error: Error) => { ...@@ -333,11 +179,7 @@ const createErrorArg = (error: Error) => {
} }
const createLogEntry = (level: LogMethod, args: any[]) => { const createLogEntry = (level: LogMethod, args: any[]) => {
// Always log to client file logger with args (formatting done inside log method) if (!shouldForwardLogs) {
clientFileLogger.log(level, args)
// Only forward to terminal if enabled
if (!isTerminalLoggingEnabled) {
return return
} }
...@@ -370,10 +212,7 @@ export const forwardErrorLog = (args: any[]) => { ...@@ -370,10 +212,7 @@ export const forwardErrorLog = (args: any[]) => {
return return
} }
// Always log to client file logger with args (formatting done inside log method) if (!shouldForwardLogs) {
clientFileLogger.log('error', args)
// Only forward to terminal if enabled
if (!isTerminalLoggingEnabled) {
return return
} }
...@@ -439,15 +278,7 @@ const getErrorStackWithOwnerStack = (error: Error) => { ...@@ -439,15 +278,7 @@ const getErrorStackWithOwnerStack = (error: Error) => {
} }
export function logUnhandledRejection(reason: unknown) { export function logUnhandledRejection(reason: unknown) {
// Always log to client file logger if (!shouldForwardLogs) {
const message =
reason instanceof Error
? `${reason.name}: ${reason.message}`
: JSON.stringify(reason)
clientFileLogger.log('error', [`unhandledRejection: ${message}`])
// Only forward to terminal if enabled
if (!isTerminalLoggingEnabled) {
return return
} }
...@@ -540,13 +371,7 @@ const isReactServerReplayedLog = (args: any[]) => { ...@@ -540,13 +371,7 @@ const isReactServerReplayedLog = (args: any[]) => {
} }
export function forwardUnhandledError(error: Error) { export function forwardUnhandledError(error: Error) {
// Always log to client file logger if (!shouldForwardLogs) {
clientFileLogger.log('error', [
`uncaughtError: ${error.name}: ${error.message}`,
])
// Only forward to terminal if enabled
if (!isTerminalLoggingEnabled) {
return return
} }
...@@ -584,12 +409,4 @@ export const initializeDebugLogForwarding = (router: 'app' | 'pages'): void => { ...@@ -584,12 +409,4 @@ export const initializeDebugLogForwarding = (router: 'app' | 'pages'): void => {
} catch {} } catch {}
logQueue.router = router logQueue.router = router
isPatched = true isPatched = true
// Cleanup on page unload
window.addEventListener('beforeunload', () => {
cancelLogFlush()
stopHeartbeat()
// Send any remaining logs before page unloads
sendClientFileLogs()
})
} }
...@@ -80,6 +80,10 @@ export class FileLogger { ...@@ -80,6 +80,10 @@ export class FileLogger {
return this.logQueue return this.logQueue
} }
public isEnabled(): boolean {
return this.mcpServerEnabled && this.isInitialized
}
private flush(): void { private flush(): void {
if (this.logQueue.length === 0) { if (this.logQueue.length === 0) {
return return
...@@ -124,11 +128,7 @@ export class FileLogger { ...@@ -124,11 +128,7 @@ export class FileLogger {
log(source: 'Server' | 'Browser', level: string, message: string): void { log(source: 'Server' | 'Browser', level: string, message: string): void {
// Don't log anything if mcpServer is disabled // Don't log anything if mcpServer is disabled
if (!this.mcpServerEnabled) { if (!this.isEnabled()) {
return
}
if (!this.isInitialized) {
return return
} }
......
import { configure } from 'next/dist/compiled/safe-stable-stringify'
import { cyan, dim, red, yellow } from '../../../lib/picocolors' import { cyan, dim, red, yellow } from '../../../lib/picocolors'
import type { Project } from '../../../build/swc/types' import type { Project } from '../../../build/swc/types'
import util from 'util' import util from 'util'
...@@ -13,7 +14,6 @@ import { ...@@ -13,7 +14,6 @@ import {
type ConsoleEntry, type ConsoleEntry,
UNDEFINED_MARKER, UNDEFINED_MARKER,
} from '../../../next-devtools/shared/forward-logs-shared' } from '../../../next-devtools/shared/forward-logs-shared'
import { formatConsoleArgs } from '../../../client/lib/console'
import { getFileLogger } from './file-logger' import { getFileLogger } from './file-logger'
export function restoreUndefined(x: any): any { export function restoreUndefined(x: any): any {
...@@ -27,23 +27,6 @@ export function restoreUndefined(x: any): any { ...@@ -27,23 +27,6 @@ export function restoreUndefined(x: any): any {
return x return x
} }
function cleanConsoleArgsForFileLogging(args: any[]): string {
/**
* Use formatConsoleArgs to strip out background and color format specifiers
* and keep only the original string content for file logging
*/
try {
return formatConsoleArgs(args)
} catch {
// Fallback to simple string conversion if formatting fails
return args
.map((arg) =>
typeof arg === 'string' ? arg : util.inspect(arg, { depth: 2 })
)
.join(' ')
}
}
const methods: Array<LogMethod> = [ const methods: Array<LogMethod> = [
'log', 'log',
'info', 'info',
...@@ -89,7 +72,7 @@ const forwardConsole: typeof console = { ...@@ -89,7 +72,7 @@ const forwardConsole: typeof console = {
), ),
} }
async function deserializeArgData(arg: any) { function deserializeArgData(arg: any) {
try { try {
// we want undefined to be represented as it would be in the browser from the user's perspective (otherwise it would be stripped away/shown as null) // we want undefined to be represented as it would be in the browser from the user's perspective (otherwise it would be stripped away/shown as null)
if (arg === UNDEFINED_MARKER) { if (arg === UNDEFINED_MARKER) {
...@@ -222,13 +205,18 @@ export function stripFormatSpecifiers(args: any[]): any[] { ...@@ -222,13 +205,18 @@ export function stripFormatSpecifiers(args: any[]): any[] {
return result return result
} }
async function prepareFormattedErrorArgs( const safeStringify = configure({ maximumDepth: 5, maximumBreadth: 100 })
entry: Extract<ServerLogEntry, { kind: 'formatted-error' }>,
ctx: MappingContext, function formatFileLogValue(arg: any): string {
distDir: string if (typeof arg === 'string') return arg
) { if (typeof arg === 'number' || typeof arg === 'boolean') return String(arg)
const mapped = await getSourceMappedStackFrames(entry.stack, ctx, distDir) if (arg === null) return 'null'
return [colorError(mapped, { prefix: entry.prefix })] if (arg === undefined) return 'undefined'
return safeStringify(arg) ?? String(arg)
}
function formatConsoleArgsForFileLogging(args: any[]): string {
return stripFormatSpecifiers(args).map(formatFileLogValue).join(' ')
} }
async function prepareConsoleArgs( async function prepareConsoleArgs(
...@@ -239,7 +227,7 @@ async function prepareConsoleArgs( ...@@ -239,7 +227,7 @@ async function prepareConsoleArgs(
const deserialized = await Promise.all( const deserialized = await Promise.all(
entry.args.map(async (arg) => { entry.args.map(async (arg) => {
if (arg.kind === 'arg') { if (arg.kind === 'arg') {
const data = await deserializeArgData(arg.data) const data = deserializeArgData(arg.data)
if (entry.method === 'warn' && typeof data === 'string') { if (entry.method === 'warn' && typeof data === 'string') {
return yellow(data) return yellow(data)
} }
...@@ -247,7 +235,7 @@ async function prepareConsoleArgs( ...@@ -247,7 +235,7 @@ async function prepareConsoleArgs(
} }
if (!arg.stack) return red(arg.prefix) if (!arg.stack) return red(arg.prefix)
const mapped = await getSourceMappedStackFrames(arg.stack, ctx, distDir) const mapped = await getSourceMappedStackFrames(arg.stack, ctx, distDir)
return colorError(mapped, { prefix: arg.prefix, applyColor: false }) return colorError(mapped, { prefix: arg.prefix })
}) })
) )
...@@ -258,16 +246,24 @@ async function prepareConsoleErrorArgs( ...@@ -258,16 +246,24 @@ async function prepareConsoleErrorArgs(
entry: Extract<ServerLogEntry, { kind: 'any-logged-error' }>, entry: Extract<ServerLogEntry, { kind: 'any-logged-error' }>,
ctx: MappingContext, ctx: MappingContext,
distDir: string distDir: string
) { ): Promise<{ terminal: any[]; fileLog: any[] }> {
const deserialized = await Promise.all( const pairs = await Promise.all(
entry.args.map(async (arg) => { entry.args.map(async (arg) => {
if (arg.kind === 'arg') { if (arg.kind === 'arg') {
if (arg.isRejectionMessage) return red(arg.data) const data = deserializeArgData(arg.data)
return deserializeArgData(arg.data) return {
terminal: arg.isRejectionMessage ? red(arg.data) : data,
fileLog: data,
}
}
if (!arg.stack) {
return { terminal: red(arg.prefix), fileLog: arg.prefix }
} }
if (!arg.stack) return red(arg.prefix)
const mapped = await getSourceMappedStackFrames(arg.stack, ctx, distDir) const mapped = await getSourceMappedStackFrames(arg.stack, ctx, distDir)
return colorError(mapped, { prefix: arg.prefix }) return {
terminal: colorError(mapped, { prefix: arg.prefix }),
fileLog: colorError(mapped, { prefix: arg.prefix, applyColor: false }),
}
}) })
) )
...@@ -283,21 +279,32 @@ async function prepareConsoleErrorArgs( ...@@ -283,21 +279,32 @@ async function prepareConsoleErrorArgs(
* - the user already knows where the console.error is at because we append the location * - the user already knows where the console.error is at because we append the location
*/ */
const location = getConsoleLocation(mappedStack) const location = getConsoleLocation(mappedStack)
if (entry.args.some((a) => a.kind === 'formatted-error-arg')) { const hasFormattedErrorArg = entry.args.some(
const result = stripFormatSpecifiers(deserialized) (a) => a.kind === 'formatted-error-arg'
)
if (hasFormattedErrorArg) {
const terminal = stripFormatSpecifiers(pairs.map((p) => p.terminal))
const fileLog = stripFormatSpecifiers(pairs.map((p) => p.fileLog))
if (location) { if (location) {
result.push(dim(`(${location})`)) terminal.push(dim(`(${location})`))
fileLog.push(`(${location})`)
} }
return result return { terminal, fileLog }
} }
const result = [ const terminal = [
...processConsoleFormatStrings(deserialized), ...processConsoleFormatStrings(pairs.map((p) => p.terminal)),
colorError(mappedStack), colorError(mappedStack),
] ]
const fileLog = [
...processConsoleFormatStrings(pairs.map((p) => p.fileLog)),
colorError(mappedStack, { applyColor: false }),
]
if (location) { if (location) {
result.push(dim(`(${location})`)) terminal.push(dim(`(${location})`))
fileLog.push(`(${location})`)
} }
return result return { terminal, fileLog }
} }
async function handleTable( async function handleTable(
...@@ -416,8 +423,7 @@ async function handleDefaultConsole( ...@@ -416,8 +423,7 @@ async function handleDefaultConsole(
browserPrefix: string, browserPrefix: string,
ctx: MappingContext, ctx: MappingContext,
distDir: string, distDir: string,
config: BrowserLogConfig, config: BrowserLogConfig
isServerLog: boolean
) { ) {
const consoleArgs = await prepareConsoleArgs(entry, ctx, distDir) const consoleArgs = await prepareConsoleArgs(entry, ctx, distDir)
const withStackEntry = await withLocation( const withStackEntry = await withLocation(
...@@ -431,18 +437,6 @@ async function handleDefaultConsole( ...@@ -431,18 +437,6 @@ async function handleDefaultConsole(
) )
const consoleMethod = forwardConsole[entry.method] || forwardConsole.log const consoleMethod = forwardConsole[entry.method] || forwardConsole.log
;(consoleMethod as (...args: any[]) => void)(browserPrefix, ...withStackEntry) ;(consoleMethod as (...args: any[]) => void)(browserPrefix, ...withStackEntry)
// Process enqueued logs and write to file
// Log to file with correct source based on context
const fileLogger = getFileLogger()
// Use cleaned console args to strip out background and color format specifiers
const message = cleanConsoleArgsForFileLogging(consoleArgs)
if (isServerLog) {
fileLogger.logServer(entry.method.toUpperCase(), message)
} else {
fileLogger.logBrowser(entry.method.toUpperCase(), message)
}
} }
type LogLevel = 'error' | 'warn' | 'verbose' type LogLevel = 'error' | 'warn' | 'verbose'
...@@ -501,6 +495,14 @@ function shouldShowEntry( ...@@ -501,6 +495,14 @@ function shouldShowEntry(
return false return false
} }
function deserializeForFileLog(a: any): any {
if (a.kind === 'arg') {
return deserializeArgData(a.data)
}
// formatted-error-arg
return a.prefix ?? ''
}
export async function handleLog( export async function handleLog(
entries: ServerLogEntry[], entries: ServerLogEntry[],
ctx: MappingContext, ctx: MappingContext,
...@@ -511,12 +513,33 @@ export async function handleLog( ...@@ -511,12 +513,33 @@ export async function handleLog(
const isServerLog = ctx.isServer || ctx.isEdgeServer const isServerLog = ctx.isServer || ctx.isEdgeServer
const browserPrefix = isServerLog ? cyan('[server]') : cyan('[browser]') const browserPrefix = isServerLog ? cyan('[server]') : cyan('[browser]')
const fileLogger = getFileLogger() const fileLogger = getFileLogger()
const shouldWriteFileLogs = fileLogger.isEnabled()
for (const entry of entries) { for (const entry of entries) {
// Filter entries based on config mode const shouldShow = shouldShowEntry(entry, config)
if (!shouldShowEntry(entry, config)) {
if (!shouldWriteFileLogs && !shouldShow) {
continue continue
} }
// Console entries: write file log from raw args (no source mapping needed)
if (shouldWriteFileLogs && entry.kind === 'console') {
try {
const message = formatConsoleArgsForFileLogging(
entry.args.map(deserializeForFileLog)
)
if (isServerLog) {
fileLogger.logServer(entry.method.toUpperCase(), message)
} else {
fileLogger.logBrowser(entry.method.toUpperCase(), message)
}
} catch {
// noop
}
}
if (!shouldShow && entry.kind === 'console') continue
try { try {
switch (entry.kind) { switch (entry.kind) {
case 'console': { case 'console': {
...@@ -559,8 +582,7 @@ export async function handleLog( ...@@ -559,8 +582,7 @@ export async function handleLog(
browserPrefix, browserPrefix,
ctx, ctx,
distDir, distDir,
config, config
isServerLog
) )
break break
} }
...@@ -572,74 +594,102 @@ export async function handleLog( ...@@ -572,74 +594,102 @@ export async function handleLog(
} }
// any logged errors are anything that are logged as "red" in the browser but aren't only an Error (console.error, Promise.reject(100)) // any logged errors are anything that are logged as "red" in the browser but aren't only an Error (console.error, Promise.reject(100))
case 'any-logged-error': { case 'any-logged-error': {
const consoleArgs = await prepareConsoleErrorArgs(entry, ctx, distDir) const { terminal, fileLog } = await prepareConsoleErrorArgs(
forwardConsole.error(browserPrefix, ...consoleArgs) entry,
ctx,
// Process enqueued logs and write to file distDir
fileLogger.logBrowser(
'ERROR',
cleanConsoleArgsForFileLogging(consoleArgs)
) )
if (shouldWriteFileLogs) {
const message = formatConsoleArgsForFileLogging(fileLog)
if (isServerLog) {
fileLogger.logServer('ERROR', message)
} else {
fileLogger.logBrowser('ERROR', message)
}
}
if (shouldShow) {
forwardConsole.error(browserPrefix, ...terminal)
}
break break
} }
// formatted error is an explicit error event (rejections, uncaught errors) // formatted error is an explicit error event (rejections, uncaught errors)
case 'formatted-error': { case 'formatted-error': {
const formattedArgs = await prepareFormattedErrorArgs( const mapped = await getSourceMappedStackFrames(
entry, entry.stack,
ctx, ctx,
distDir distDir
) )
forwardConsole.error(browserPrefix, ...formattedArgs) if (shouldWriteFileLogs) {
const message =
// Process enqueued logs and write to file colorError(mapped, { prefix: entry.prefix, applyColor: false }) ||
fileLogger.logBrowser( ''
'ERROR', if (isServerLog) {
cleanConsoleArgsForFileLogging(formattedArgs) fileLogger.logServer('ERROR', message)
) } else {
fileLogger.logBrowser('ERROR', message)
}
}
if (shouldShow) {
forwardConsole.error(
browserPrefix,
colorError(mapped, { prefix: entry.prefix })
)
}
break break
} }
default: { default: {
} }
} }
} catch { } catch {
switch (entry.kind) { // Source mapping failed — write best-effort message-only file log for errors
case 'any-logged-error': { if (shouldWriteFileLogs && entry.kind !== 'console') {
const consoleArgs = await prepareConsoleErrorArgs(entry, ctx, distDir) try {
forwardConsole.error(browserPrefix, ...consoleArgs) const message =
// Process enqueued logs and write to file entry.kind === 'formatted-error'
fileLogger.logBrowser( ? entry.prefix
'ERROR', : formatConsoleArgsForFileLogging(
cleanConsoleArgsForFileLogging(consoleArgs) entry.args.map(deserializeForFileLog)
) )
break if (isServerLog) {
} fileLogger.logServer('ERROR', message)
case 'console': { } else {
const consoleMethod = fileLogger.logBrowser('ERROR', message)
forwardConsole[entry.method] || forwardConsole.log }
const consoleArgs = await prepareConsoleArgs(entry, ctx, distDir) } catch {
;(consoleMethod as (...args: any[]) => void)( // noop
browserPrefix,
...consoleArgs
)
// Process enqueued logs and write to file
fileLogger.logBrowser(
'ERROR',
cleanConsoleArgsForFileLogging(consoleArgs)
)
break
}
case 'formatted-error': {
forwardConsole.error(browserPrefix, `${entry.prefix}\n`, entry.stack)
// Process enqueued logs and write to file
fileLogger.logBrowser(
'ERROR',
cleanConsoleArgsForFileLogging([`${entry.prefix}\n${entry.stack}`])
)
break
} }
default: { }
if (shouldShow) {
switch (entry.kind) {
case 'any-logged-error': {
const { terminal } = await prepareConsoleErrorArgs(
entry,
ctx,
distDir
)
forwardConsole.error(browserPrefix, ...terminal)
break
}
case 'console': {
const consoleMethod =
forwardConsole[entry.method] || forwardConsole.log
const consoleArgs = await prepareConsoleArgs(entry, ctx, distDir)
;(consoleMethod as (...args: any[]) => void)(
browserPrefix,
...consoleArgs
)
break
}
case 'formatted-error': {
forwardConsole.error(
browserPrefix,
`${entry.prefix}\n`,
entry.stack
)
break
}
default: {
}
} }
} }
} }
...@@ -713,14 +763,3 @@ export async function receiveBrowserLogsTurbopack(opts: { ...@@ -713,14 +763,3 @@ export async function receiveBrowserLogsTurbopack(opts: {
await handleLog(entries, ctx, distDir, opts.config) await handleLog(entries, ctx, distDir, opts.config)
} }
// Handle client file logs (always logged regardless of terminal flag)
export async function handleClientFileLogs(
logs: Array<{ timestamp: string; level: string; message: string }>
): Promise<void> {
const fileLogger = getFileLogger()
for (const log of logs) {
fileLogger.logBrowser(log.level, log.message)
}
}
...@@ -105,10 +105,7 @@ import { getRestartDevServerMiddleware } from '../../next-devtools/server/restar ...@@ -105,10 +105,7 @@ import { getRestartDevServerMiddleware } from '../../next-devtools/server/restar
import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compilation-events' import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compilation-events'
import { getSupportedBrowsers } from '../../build/get-supported-browsers' import { getSupportedBrowsers } from '../../build/get-supported-browsers'
import { printBuildErrors } from '../../build/print-build-errors' import { printBuildErrors } from '../../build/print-build-errors'
import { import { receiveBrowserLogsTurbopack } from './browser-logs/receive-logs'
receiveBrowserLogsTurbopack,
handleClientFileLogs,
} from './browser-logs/receive-logs'
import { normalizePath } from '../../lib/normalize-path' import { normalizePath } from '../../lib/normalize-path'
import { import {
devToolsConfigMiddleware, devToolsConfigMiddleware,
...@@ -1263,24 +1260,18 @@ export async function createHotReloaderTurbopack( ...@@ -1263,24 +1260,18 @@ export async function createHotReloaderTurbopack(
// TODO // TODO
break break
case 'browser-logs': { case 'browser-logs': {
const browserToTerminalConfig = await receiveBrowserLogsTurbopack({
nextConfig.logging && nextConfig.logging.browserToTerminal entries: parsedData.entries,
if (browserToTerminalConfig) { router: parsedData.router,
await receiveBrowserLogsTurbopack({ sourceType: parsedData.sourceType,
entries: parsedData.entries, project,
router: parsedData.router, projectPath,
sourceType: parsedData.sourceType, distDir,
project, config:
projectPath, (nextConfig.logging &&
distDir, nextConfig.logging.browserToTerminal) ||
config: browserToTerminalConfig, false,
}) })
}
break
}
case 'client-file-logs': {
// Always log to file regardless of terminal flag
await handleClientFileLogs(parsedData.logs)
break break
} }
case 'ping': { case 'ping': {
......
...@@ -89,10 +89,7 @@ import { getDisableDevIndicatorMiddleware } from '../../next-devtools/server/dev ...@@ -89,10 +89,7 @@ import { getDisableDevIndicatorMiddleware } from '../../next-devtools/server/dev
import getWebpackBundler from '../../shared/lib/get-webpack-bundler' import getWebpackBundler from '../../shared/lib/get-webpack-bundler'
import { getRestartDevServerMiddleware } from '../../next-devtools/server/restart-dev-server-middleware' import { getRestartDevServerMiddleware } from '../../next-devtools/server/restart-dev-server-middleware'
import { checkFileSystemCacheInvalidationAndCleanup } from '../../build/webpack/cache-invalidation' import { checkFileSystemCacheInvalidationAndCleanup } from '../../build/webpack/cache-invalidation'
import { import { receiveBrowserLogsWebpack } from './browser-logs/receive-logs'
receiveBrowserLogsWebpack,
handleClientFileLogs,
} from './browser-logs/receive-logs'
import { import {
devToolsConfigMiddleware, devToolsConfigMiddleware,
getDevToolsConfig, getDevToolsConfig,
...@@ -604,26 +601,20 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -604,26 +601,20 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
break break
} }
case 'browser-logs': { case 'browser-logs': {
const browserToTerminalConfig = await receiveBrowserLogsWebpack({
this.config.logging && this.config.logging.browserToTerminal entries: payload.entries,
if (browserToTerminalConfig) { router: payload.router,
await receiveBrowserLogsWebpack({ sourceType: payload.sourceType,
entries: payload.entries, clientStats: () => this.clientStats,
router: payload.router, serverStats: () => this.serverStats,
sourceType: payload.sourceType, edgeServerStats: () => this.edgeServerStats,
clientStats: () => this.clientStats, rootDirectory: this.dir,
serverStats: () => this.serverStats, distDir: this.distDir,
edgeServerStats: () => this.edgeServerStats, config:
rootDirectory: this.dir, (this.config.logging &&
distDir: this.distDir, this.config.logging.browserToTerminal) ||
config: browserToTerminalConfig, false,
}) })
}
break
}
case 'client-file-logs': {
// Always log to file regardless of terminal flag
await handleClientFileLogs(payload.logs)
break break
} }
case 'ping': { case 'ping': {
......
...@@ -137,12 +137,10 @@ describe('log-file', () => { ...@@ -137,12 +137,10 @@ describe('log-file', () => {
// Only browser only logs are being forwarded to terminal // Only browser only logs are being forwarded to terminal
expect(newLogContent).toMatchInlineSnapshot(` expect(newLogContent).toMatchInlineSnapshot(`
"{"timestamp":"xx:xx:xx.xxx","source":"Browser","level":"LOG","message":"Client: Complex circular object: {\\"data\\":{\\"nested\\":{\\"items\\":[1,2,3],\\"value\\":42},\\"parent\\":\\"[Circular]\\"},\\"metadata\\":{\\"name\\":\\"safe stringify\\",\\"version\\":\\"1.0.0\\"},\\"name\\":\\"test\\"}"} "{"timestamp":"xx:xx:xx.xxx","source":"Browser","level":"LOG","message":"Client: Complex circular object: {\\"data\\":{\\"nested\\":{\\"items\\":[1,2,3],\\"value\\":42},\\"parent\\":\\"[Circular]\\"},\\"metadata\\":{\\"name\\":\\"safe stringify\\",\\"version\\":\\"1.0.0\\"},\\"name\\":\\"test\\"}"}
{"timestamp":"xx:xx:xx.xxx","source":"Browser","level":"ERROR","message":"Client: This is an error message from client component"} {"timestamp":"xx:xx:xx.xxx","source":"Browser","level":"ERROR","message":"Client: This is an error message from client component \\n at ClientPage.useEffect (app/client/page.tsx:25:13)\\n 23 | circularObj.data.parent = circularObj\\n 24 | console.log('Client: Complex circular object:', circularObj)\\n> 25 | console.error('Client: This is an error message from client component')\\n | ^\\n 26 | console.warn('Client: This is a warning message from client component')\\n 27 | }, [])\\n 28 | (app/client/page.tsx:25:13)"}
{"timestamp":"xx:xx:xx.xxx","source":"Browser","level":"WARN","message":"Client: This is a warning message from client component"}
{"timestamp":"xx:xx:xx.xxx","source":"Server","level":"ERROR","message":"[browser] \\"Client: This is an error message from client component\\" \\"\\\\n at ClientPage.useEffect (app/client/page.tsx:25:13)\\\\n 23 | circularObj.data.parent = circularObj\\\\n 24 | console.log('Client: Complex circular object:', circularObj)\\\\n> 25 | console.error('Client: This is an error message from client component')\\\\n | ^\\\\n 26 | console.warn('Client: This is a warning message from client component')\\\\n 27 | }, [])\\\\n 28 |\\" \\"(app/client/page.tsx:25:13)\\""} {"timestamp":"xx:xx:xx.xxx","source":"Server","level":"ERROR","message":"[browser] \\"Client: This is an error message from client component\\" \\"\\\\n at ClientPage.useEffect (app/client/page.tsx:25:13)\\\\n 23 | circularObj.data.parent = circularObj\\\\n 24 | console.log('Client: Complex circular object:', circularObj)\\\\n> 25 | console.error('Client: This is an error message from client component')\\\\n | ^\\\\n 26 | console.warn('Client: This is a warning message from client component')\\\\n 27 | }, [])\\\\n 28 |\\" \\"(app/client/page.tsx:25:13)\\""}
{"timestamp":"xx:xx:xx.xxx","source":"Browser","level":"ERROR","message":"Client: This is an error message from client component \\"\\\\n at ClientPage.useEffect (app/client/page.tsx:25:13)\\\\n 23 | circularObj.data.parent = circularObj\\\\n 24 | console.log('Client: Complex circular object:', circularObj)\\\\n> 25 | console.error('Client: This is an error message from client component')\\\\n | ^\\\\n 26 | console.warn('Client: This is a warning message from client component')\\\\n 27 | }, [])\\\\n 28 |\\" \\"(app/client/page.tsx:25:13)\\""} {"timestamp":"xx:xx:xx.xxx","source":"Browser","level":"WARN","message":"Client: This is a warning message from client component"}
{"timestamp":"xx:xx:xx.xxx","source":"Server","level":"WARN","message":"[browser] \\"Client: This is a warning message from client component\\" \\"(app/client/page.tsx:26:13)\\""} {"timestamp":"xx:xx:xx.xxx","source":"Server","level":"WARN","message":"[browser] \\"Client: This is a warning message from client component\\" \\"(app/client/page.tsx:26:13)\\""}"
{"timestamp":"xx:xx:xx.xxx","source":"Browser","level":"WARN","message":"Client: This is a warning message from client component"}"
`) `)
}) })
} else { } else {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment