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 {
type LogMethod,
patchConsoleMethod,
} from '../../shared/forward-logs-shared'
import {
preLogSerializationClone,
logStringify,
safeStringifyWithDepth,
} from './forward-logs-utils'
import { preLogSerializationClone, logStringify } from './forward-logs-utils'
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 shouldForwardLogs =
isTerminalLoggingEnabled || !!process.env.__NEXT_MCP_SERVER
const methods: Array<LogMethod> = [
'log',
......@@ -175,30 +66,22 @@ const serializeEntries = (entries: Array<ClientLogEntry>) =>
}
})
// Function to send client file logs to server
const sendClientFileLogs = () => {
if (!logQueue.socket || logQueue.socket.readyState !== WebSocket.OPEN) {
return
}
const logs = clientFileLogger.getLogs()
if (logs.length === 0) {
const flushBufferedEntries = (socket: WebSocket) => {
if (logQueue.entries.length === 0) {
return
}
try {
const payload = JSON.stringify({
event: 'client-file-logs',
logs: logs,
})
const payload = JSON.stringify({
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,
})
logQueue.socket.send(payload)
} catch (error) {
console.error(error)
} finally {
// Clear logs regardless of send success to prevent memory leaks
clientFileLogger.clear()
}
socket.send(payload)
logQueue.entries = []
logQueue.sourceType = undefined
}
// Combined state and public API
......@@ -238,20 +121,7 @@ export const logQueue: {
// just incase
try {
const payload = JSON.stringify({
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()
flushBufferedEntries(socket)
} catch {
// error (make sure u don't infinite loop)
/* noop */
......@@ -261,7 +131,7 @@ export const logQueue: {
onSocketReady: (socket: WebSocket) => {
// When MCP or terminal logging is enabled, we enable the socket connection,
// otherwise it will not proceed.
if (!isTerminalLoggingEnabled && !process.env.__NEXT_MCP_SERVER) {
if (!shouldForwardLogs) {
return
}
if (socket.readyState !== WebSocket.OPEN) {
......@@ -273,35 +143,11 @@ export const logQueue: {
logQueue.cancelFlush?.()
logQueue.socket = socket
// Add socket event listeners to track connection state
socket.addEventListener('close', () => {
cancelLogFlush()
stopHeartbeat()
})
// 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 */
}
try {
flushBufferedEntries(socket)
} 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) => {
}
const createLogEntry = (level: LogMethod, args: any[]) => {
// Always log to client file logger with args (formatting done inside log method)
clientFileLogger.log(level, args)
// Only forward to terminal if enabled
if (!isTerminalLoggingEnabled) {
if (!shouldForwardLogs) {
return
}
......@@ -370,10 +212,7 @@ export const forwardErrorLog = (args: any[]) => {
return
}
// Always log to client file logger with args (formatting done inside log method)
clientFileLogger.log('error', args)
// Only forward to terminal if enabled
if (!isTerminalLoggingEnabled) {
if (!shouldForwardLogs) {
return
}
......@@ -439,15 +278,7 @@ const getErrorStackWithOwnerStack = (error: Error) => {
}
export function logUnhandledRejection(reason: unknown) {
// Always log to client file logger
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) {
if (!shouldForwardLogs) {
return
}
......@@ -540,13 +371,7 @@ const isReactServerReplayedLog = (args: any[]) => {
}
export function forwardUnhandledError(error: Error) {
// Always log to client file logger
clientFileLogger.log('error', [
`uncaughtError: ${error.name}: ${error.message}`,
])
// Only forward to terminal if enabled
if (!isTerminalLoggingEnabled) {
if (!shouldForwardLogs) {
return
}
......@@ -584,12 +409,4 @@ export const initializeDebugLogForwarding = (router: 'app' | 'pages'): void => {
} catch {}
logQueue.router = router
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 {
return this.logQueue
}
public isEnabled(): boolean {
return this.mcpServerEnabled && this.isInitialized
}
private flush(): void {
if (this.logQueue.length === 0) {
return
......@@ -124,11 +128,7 @@ export class FileLogger {
log(source: 'Server' | 'Browser', level: string, message: string): void {
// Don't log anything if mcpServer is disabled
if (!this.mcpServerEnabled) {
return
}
if (!this.isInitialized) {
if (!this.isEnabled()) {
return
}
......
import { configure } from 'next/dist/compiled/safe-stable-stringify'
import { cyan, dim, red, yellow } from '../../../lib/picocolors'
import type { Project } from '../../../build/swc/types'
import util from 'util'
......@@ -13,7 +14,6 @@ import {
type ConsoleEntry,
UNDEFINED_MARKER,
} from '../../../next-devtools/shared/forward-logs-shared'
import { formatConsoleArgs } from '../../../client/lib/console'
import { getFileLogger } from './file-logger'
export function restoreUndefined(x: any): any {
......@@ -27,23 +27,6 @@ export function restoreUndefined(x: any): any {
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> = [
'log',
'info',
......@@ -89,7 +72,7 @@ const forwardConsole: typeof console = {
),
}
async function deserializeArgData(arg: any) {
function deserializeArgData(arg: any) {
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)
if (arg === UNDEFINED_MARKER) {
......@@ -222,13 +205,18 @@ export function stripFormatSpecifiers(args: any[]): any[] {
return result
}
async function prepareFormattedErrorArgs(
entry: Extract<ServerLogEntry, { kind: 'formatted-error' }>,
ctx: MappingContext,
distDir: string
) {
const mapped = await getSourceMappedStackFrames(entry.stack, ctx, distDir)
return [colorError(mapped, { prefix: entry.prefix })]
const safeStringify = configure({ maximumDepth: 5, maximumBreadth: 100 })
function formatFileLogValue(arg: any): string {
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'
return safeStringify(arg) ?? String(arg)
}
function formatConsoleArgsForFileLogging(args: any[]): string {
return stripFormatSpecifiers(args).map(formatFileLogValue).join(' ')
}
async function prepareConsoleArgs(
......@@ -239,7 +227,7 @@ async function prepareConsoleArgs(
const deserialized = await Promise.all(
entry.args.map(async (arg) => {
if (arg.kind === 'arg') {
const data = await deserializeArgData(arg.data)
const data = deserializeArgData(arg.data)
if (entry.method === 'warn' && typeof data === 'string') {
return yellow(data)
}
......@@ -247,7 +235,7 @@ async function prepareConsoleArgs(
}
if (!arg.stack) return red(arg.prefix)
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(
entry: Extract<ServerLogEntry, { kind: 'any-logged-error' }>,
ctx: MappingContext,
distDir: string
) {
const deserialized = await Promise.all(
): Promise<{ terminal: any[]; fileLog: any[] }> {
const pairs = await Promise.all(
entry.args.map(async (arg) => {
if (arg.kind === 'arg') {
if (arg.isRejectionMessage) return red(arg.data)
return deserializeArgData(arg.data)
const data = 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)
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(
* - the user already knows where the console.error is at because we append the location
*/
const location = getConsoleLocation(mappedStack)
if (entry.args.some((a) => a.kind === 'formatted-error-arg')) {
const result = stripFormatSpecifiers(deserialized)
const hasFormattedErrorArg = entry.args.some(
(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) {
result.push(dim(`(${location})`))
terminal.push(dim(`(${location})`))
fileLog.push(`(${location})`)
}
return result
return { terminal, fileLog }
}
const result = [
...processConsoleFormatStrings(deserialized),
const terminal = [
...processConsoleFormatStrings(pairs.map((p) => p.terminal)),
colorError(mappedStack),
]
const fileLog = [
...processConsoleFormatStrings(pairs.map((p) => p.fileLog)),
colorError(mappedStack, { applyColor: false }),
]
if (location) {
result.push(dim(`(${location})`))
terminal.push(dim(`(${location})`))
fileLog.push(`(${location})`)
}
return result
return { terminal, fileLog }
}
async function handleTable(
......@@ -416,8 +423,7 @@ async function handleDefaultConsole(
browserPrefix: string,
ctx: MappingContext,
distDir: string,
config: BrowserLogConfig,
isServerLog: boolean
config: BrowserLogConfig
) {
const consoleArgs = await prepareConsoleArgs(entry, ctx, distDir)
const withStackEntry = await withLocation(
......@@ -431,18 +437,6 @@ async function handleDefaultConsole(
)
const consoleMethod = forwardConsole[entry.method] || forwardConsole.log
;(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'
......@@ -501,6 +495,14 @@ function shouldShowEntry(
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(
entries: ServerLogEntry[],
ctx: MappingContext,
......@@ -511,12 +513,33 @@ export async function handleLog(
const isServerLog = ctx.isServer || ctx.isEdgeServer
const browserPrefix = isServerLog ? cyan('[server]') : cyan('[browser]')
const fileLogger = getFileLogger()
const shouldWriteFileLogs = fileLogger.isEnabled()
for (const entry of entries) {
// Filter entries based on config mode
if (!shouldShowEntry(entry, config)) {
const shouldShow = shouldShowEntry(entry, config)
if (!shouldWriteFileLogs && !shouldShow) {
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 {
switch (entry.kind) {
case 'console': {
......@@ -559,8 +582,7 @@ export async function handleLog(
browserPrefix,
ctx,
distDir,
config,
isServerLog
config
)
break
}
......@@ -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))
case 'any-logged-error': {
const consoleArgs = await prepareConsoleErrorArgs(entry, ctx, distDir)
forwardConsole.error(browserPrefix, ...consoleArgs)
// Process enqueued logs and write to file
fileLogger.logBrowser(
'ERROR',
cleanConsoleArgsForFileLogging(consoleArgs)
const { terminal, fileLog } = await prepareConsoleErrorArgs(
entry,
ctx,
distDir
)
if (shouldWriteFileLogs) {
const message = formatConsoleArgsForFileLogging(fileLog)
if (isServerLog) {
fileLogger.logServer('ERROR', message)
} else {
fileLogger.logBrowser('ERROR', message)
}
}
if (shouldShow) {
forwardConsole.error(browserPrefix, ...terminal)
}
break
}
// formatted error is an explicit error event (rejections, uncaught errors)
case 'formatted-error': {
const formattedArgs = await prepareFormattedErrorArgs(
entry,
const mapped = await getSourceMappedStackFrames(
entry.stack,
ctx,
distDir
)
forwardConsole.error(browserPrefix, ...formattedArgs)
// Process enqueued logs and write to file
fileLogger.logBrowser(
'ERROR',
cleanConsoleArgsForFileLogging(formattedArgs)
)
if (shouldWriteFileLogs) {
const message =
colorError(mapped, { prefix: entry.prefix, applyColor: false }) ||
''
if (isServerLog) {
fileLogger.logServer('ERROR', message)
} else {
fileLogger.logBrowser('ERROR', message)
}
}
if (shouldShow) {
forwardConsole.error(
browserPrefix,
colorError(mapped, { prefix: entry.prefix })
)
}
break
}
default: {
}
}
} catch {
switch (entry.kind) {
case 'any-logged-error': {
const consoleArgs = await prepareConsoleErrorArgs(entry, ctx, distDir)
forwardConsole.error(browserPrefix, ...consoleArgs)
// Process enqueued logs and write to file
fileLogger.logBrowser(
'ERROR',
cleanConsoleArgsForFileLogging(consoleArgs)
)
break
}
case 'console': {
const consoleMethod =
forwardConsole[entry.method] || forwardConsole.log
const consoleArgs = await prepareConsoleArgs(entry, ctx, distDir)
;(consoleMethod as (...args: any[]) => void)(
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
// Source mapping failed — write best-effort message-only file log for errors
if (shouldWriteFileLogs && entry.kind !== 'console') {
try {
const message =
entry.kind === 'formatted-error'
? entry.prefix
: formatConsoleArgsForFileLogging(
entry.args.map(deserializeForFileLog)
)
if (isServerLog) {
fileLogger.logServer('ERROR', message)
} else {
fileLogger.logBrowser('ERROR', message)
}
} catch {
// noop
}
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: {
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
import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compilation-events'
import { getSupportedBrowsers } from '../../build/get-supported-browsers'
import { printBuildErrors } from '../../build/print-build-errors'
import {
receiveBrowserLogsTurbopack,
handleClientFileLogs,
} from './browser-logs/receive-logs'
import { receiveBrowserLogsTurbopack } from './browser-logs/receive-logs'
import { normalizePath } from '../../lib/normalize-path'
import {
devToolsConfigMiddleware,
......@@ -1263,24 +1260,18 @@ export async function createHotReloaderTurbopack(
// TODO
break
case 'browser-logs': {
const browserToTerminalConfig =
nextConfig.logging && nextConfig.logging.browserToTerminal
if (browserToTerminalConfig) {
await receiveBrowserLogsTurbopack({
entries: parsedData.entries,
router: parsedData.router,
sourceType: parsedData.sourceType,
project,
projectPath,
distDir,
config: browserToTerminalConfig,
})
}
break
}
case 'client-file-logs': {
// Always log to file regardless of terminal flag
await handleClientFileLogs(parsedData.logs)
await receiveBrowserLogsTurbopack({
entries: parsedData.entries,
router: parsedData.router,
sourceType: parsedData.sourceType,
project,
projectPath,
distDir,
config:
(nextConfig.logging &&
nextConfig.logging.browserToTerminal) ||
false,
})
break
}
case 'ping': {
......
......@@ -89,10 +89,7 @@ import { getDisableDevIndicatorMiddleware } from '../../next-devtools/server/dev
import getWebpackBundler from '../../shared/lib/get-webpack-bundler'
import { getRestartDevServerMiddleware } from '../../next-devtools/server/restart-dev-server-middleware'
import { checkFileSystemCacheInvalidationAndCleanup } from '../../build/webpack/cache-invalidation'
import {
receiveBrowserLogsWebpack,
handleClientFileLogs,
} from './browser-logs/receive-logs'
import { receiveBrowserLogsWebpack } from './browser-logs/receive-logs'
import {
devToolsConfigMiddleware,
getDevToolsConfig,
......@@ -604,26 +601,20 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
break
}
case 'browser-logs': {
const browserToTerminalConfig =
this.config.logging && this.config.logging.browserToTerminal
if (browserToTerminalConfig) {
await receiveBrowserLogsWebpack({
entries: payload.entries,
router: payload.router,
sourceType: payload.sourceType,
clientStats: () => this.clientStats,
serverStats: () => this.serverStats,
edgeServerStats: () => this.edgeServerStats,
rootDirectory: this.dir,
distDir: this.distDir,
config: browserToTerminalConfig,
})
}
break
}
case 'client-file-logs': {
// Always log to file regardless of terminal flag
await handleClientFileLogs(payload.logs)
await receiveBrowserLogsWebpack({
entries: payload.entries,
router: payload.router,
sourceType: payload.sourceType,
clientStats: () => this.clientStats,
serverStats: () => this.serverStats,
edgeServerStats: () => this.edgeServerStats,
rootDirectory: this.dir,
distDir: this.distDir,
config:
(this.config.logging &&
this.config.logging.browserToTerminal) ||
false,
})
break
}
case 'ping': {
......
......@@ -137,12 +137,10 @@ describe('log-file', () => {
// Only browser only logs are being forwarded to terminal
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":"ERROR","message":"Client: This is an error message from client component"}
{"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":"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":"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":"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"}"
{"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)\\""}"
`)
})
} 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