Unverified Commit 8cfdcacf authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Log browser error and warnings in terminal (#88352)

parent 3aad67b7
......@@ -14,8 +14,11 @@ export function patchConsoleError() {
}
window.console.error = function error(...args: any[]) {
let maybeError: unknown
let isReplayedLog = false
if (process.env.NODE_ENV !== 'production') {
const { error: replayedError } = parseConsoleArgs(args)
const { error: replayedError, environmentName } = parseConsoleArgs(args)
// If environmentName is set, this is a server log replayed by React in the browser
isReplayedLog = !!environmentName
if (replayedError) {
maybeError = replayedError
} else if (isError(args[0])) {
......@@ -37,7 +40,10 @@ export function patchConsoleError() {
args
)
}
forwardErrorLog(args)
// Don't forward replayed server logs to terminal - they were already logged on the server
if (!isReplayedLog) {
forwardErrorLog(args)
}
originConsoleError.apply(window.console, args)
}
......
import {
getOwnerStack,
setOwnerStackIfAvailable,
} from './errors/stitched-error'
import { getErrorSource } from '../../../shared/lib/error-source'
import { getIsTerminalLoggingEnabled } from './terminal-logging-config'
import {
......@@ -328,7 +324,7 @@ const stringifyUserArg = (
}
const createErrorArg = (error: Error) => {
const stack = stackWithOwners(error)
const stack = getErrorStack(error)
return {
kind: 'formatted-error-arg' as const,
prefix: error.message ? `${error.name}: ${error.message}` : `${error.name}`,
......@@ -347,7 +343,7 @@ const createLogEntry = (level: LogMethod, args: any[]) => {
// do not abstract this, it implicitly relies on which functions call it. forcing the inlined implementation makes you think about callers
// error capture stack trace maybe
const stack = stackWithOwners(new Error())
const stack = getErrorStack(new Error())
const stackLines = stack?.split('\n')
const cleanStack = stackLines?.slice(3).join('\n') // this is probably ignored anyways
const entry: ConsoleEntry<unknown> = {
......@@ -369,6 +365,11 @@ const createLogEntry = (level: LogMethod, args: any[]) => {
}
export const forwardErrorLog = (args: any[]) => {
// Skip React server replayed logs - they were already logged on the server
if (isReactServerReplayedLog(args)) {
return
}
// Always log to client file logger with args (formatting done inside log method)
clientFileLogger.log('error', args)
// Only forward to terminal if enabled
......@@ -389,7 +390,7 @@ export const forwardErrorLog = (args: any[]) => {
*
* do not abstract this, it implicitly relies on which functions call it. forcing the inlined implementation makes you think about callers
*/
const stack = stackWithOwners(new Error())
const stack = getErrorStack(new Error())
const stackLines = stack?.split('\n')
const cleanStack = stackLines?.slice(3).join('\n')
......@@ -426,12 +427,8 @@ const createUncaughtErrorEntry = (
logQueue.scheduleLogSend(entry)
}
const stackWithOwners = (error: Error) => {
let ownerStack = ''
setOwnerStackIfAvailable(error)
ownerStack = getOwnerStack(error) || ''
const stack = (error.stack || '') + ownerStack
return stack
const getErrorStack = (error: Error) => {
return error.stack || ''
}
export function logUnhandledRejection(reason: unknown) {
......@@ -448,7 +445,7 @@ export function logUnhandledRejection(reason: unknown) {
}
if (reason instanceof Error) {
createUnhandledRejectionErrorEntry(reason, stackWithOwners(reason))
createUnhandledRejectionErrorEntry(reason, getErrorStack(reason))
return
}
createUnhandledRejectionNonErrorEntry(reason)
......@@ -543,7 +540,7 @@ export function forwardUnhandledError(error: Error) {
return
}
createUncaughtErrorEntry(error.name, error.message, stackWithOwners(error))
createUncaughtErrorEntry(error.name, error.message, getErrorStack(error))
}
// TODO: this router check is brittle, we need to update based on the current router the user is using
......
......@@ -340,7 +340,9 @@ export const experimentalSchema = {
browserDebugInfoInTerminal: z
.union([
z.boolean(),
z.enum(['error', 'warn', 'verbose']),
z.object({
level: z.enum(['error', 'warn', 'verbose']).optional(),
depthLimit: z.number().int().positive().optional(),
edgeLimit: z.number().int().positive().optional(),
showSourceLocation: z.boolean().optional(),
......
......@@ -757,11 +757,27 @@ export interface ExperimentalConfig {
globalNotFound?: boolean
/**
* Enable debug information to be forwarded from browser to dev server stdout/stderr
* Enable debug information to be forwarded from browser to dev server stdout/stderr.
*
* - `'warn'` (default): Forward warnings and errors to terminal
* - `'error'`: Forward only errors to terminal
* - `'verbose'`: Forward all browser console output to terminal
* - `true`: Same as 'verbose' - forward all browser console output to terminal
* - `false`: Disable browser log forwarding to terminal
* - Object: Enable with custom configuration
*/
browserDebugInfoInTerminal?:
| boolean
| 'error'
| 'warn'
| 'verbose'
| {
/**
* Minimum log level to show in terminal.
* @default 'verbose' (for object config, to preserve backward compatibility)
*/
level?: 'error' | 'warn' | 'verbose'
/**
* Option to limit stringification at a specific nesting depth when logging circular objects.
* @default 5
......@@ -1570,7 +1586,7 @@ export const defaultConfig = Object.freeze({
useCache: undefined,
slowModuleDetection: undefined,
globalNotFound: false,
browserDebugInfoInTerminal: false,
browserDebugInfoInTerminal: 'warn',
lockDistDir: true,
isolatedDevBuild: true,
proxyClientMaxBodySize: 10_485_760, // 10MB
......
......@@ -416,7 +416,7 @@ async function handleDefaultConsole(
browserPrefix: string,
ctx: MappingContext,
distDir: string,
config: boolean | { logDepth?: number; showSourceLocation?: boolean },
config: BrowserLogConfig,
isServerLog: boolean
) {
const consoleArgs = await prepareConsoleArgs(entry, ctx, distDir)
......@@ -445,11 +445,77 @@ async function handleDefaultConsole(
}
}
type LogLevel = 'error' | 'warn' | 'verbose'
type BrowserLogConfig =
| boolean
| LogLevel
| { level?: LogLevel; showSourceLocation?: boolean }
// Log levels from most severe to least severe
// Lower index = more severe
const LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {
error: 0,
warn: 1,
verbose: 2,
}
// Map console methods to log levels
const METHOD_TO_LEVEL: Record<string, LogLevel> = {
error: 'error',
warn: 'warn',
info: 'verbose',
log: 'verbose',
debug: 'verbose',
table: 'verbose',
trace: 'verbose',
dir: 'verbose',
dirxml: 'verbose',
assert: 'error',
group: 'verbose',
groupCollapsed: 'verbose',
groupEnd: 'verbose',
}
function shouldShowEntry(
entry: ServerLogEntry,
config: BrowserLogConfig
): boolean {
// If config is false, don't show any entries
if (config === false) {
return false
}
// Determine the effective minimum log level
const minLevel: LogLevel =
typeof config === 'string'
? config
: config === true
? 'verbose' // true means show everything
: typeof config === 'object'
? (config.level ?? 'verbose') // object config defaults to verbose for backward compatibility
: 'warn' // default for new installations
const minPriority = LOG_LEVEL_PRIORITY[minLevel]
// formatted-error and any-logged-error are always treated as errors
if (entry.kind === 'formatted-error' || entry.kind === 'any-logged-error') {
return LOG_LEVEL_PRIORITY['error'] <= minPriority
}
if (entry.kind === 'console') {
const entryLevel = METHOD_TO_LEVEL[entry.method] || 'log'
return LOG_LEVEL_PRIORITY[entryLevel] <= minPriority
}
return false
}
export async function handleLog(
entries: ServerLogEntry[],
ctx: MappingContext,
distDir: string,
config: boolean | { logDepth?: number; showSourceLocation?: boolean }
config: BrowserLogConfig
): Promise<void> {
// Determine the source based on the context
const isServerLog = ctx.isServer || ctx.isEdgeServer
......@@ -457,6 +523,10 @@ export async function handleLog(
const fileLogger = getFileLogger()
for (const entry of entries) {
// Filter entries based on config mode
if (!shouldShowEntry(entry, config)) {
continue
}
try {
switch (entry.kind) {
case 'console': {
......@@ -596,7 +666,7 @@ export async function receiveBrowserLogsWebpack(opts: {
edgeServerStats: () => any
rootDirectory: string
distDir: string
config: boolean | { logDepth?: number; showSourceLocation?: boolean }
config: BrowserLogConfig
}): Promise<void> {
const {
entries,
......@@ -634,7 +704,7 @@ export async function receiveBrowserLogsTurbopack(opts: {
project: Project
projectPath: string
distDir: string
config: boolean | { logDepth?: number; showSourceLocation?: boolean }
config: BrowserLogConfig
}): Promise<void> {
const { entries, router, sourceType, project, projectPath, distDir } = opts
......
......@@ -261,7 +261,12 @@ export const withLocation = async (
},
ctx: MappingContext,
distDir: string,
config: boolean | { logDepth?: number; showSourceLocation?: boolean }
config:
| boolean
| 'error'
| 'warn'
| 'verbose'
| { level?: 'error' | 'warn' | 'verbose'; showSourceLocation?: boolean }
) => {
if (typeof config === 'object' && config.showSourceLocation === false) {
return original
......
......@@ -633,6 +633,20 @@ describe('ReactRefreshLogBox', () => {
],
}
`)
} else if (isTurbopack) {
await expect(browser).toDisplayRedbox(`
{
"description": "",
"environmentLabel": null,
"label": "Runtime Error",
"source": "Child.js (4:11) @ ClickCount.render
> 4 | throw new Error()
| ^",
"stack": [
"ClickCount.render Child.js (4:11)",
],
}
`)
} else {
await expect(browser).toDisplayRedbox(`
{
......
......@@ -313,6 +313,20 @@ describe('pages/ error recovery', () => {
],
}
`)
} else if (isTurbopack) {
await expect(browser).toDisplayRedbox(`
{
"description": "oops",
"environmentLabel": null,
"label": "Runtime Error",
"source": "child.js (3:9) @ Child
> 3 | throw new Error('oops')
| ^",
"stack": [
"Child child.js (3:9)",
],
}
`)
} else {
await expect(browser).toDisplayRedbox(`
{
......
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
import { useEffect } from 'react'
export default function Page() {
useEffect(() => {
console.log('browser log: this is a log message')
console.info('browser info: this is an info message')
console.warn('browser warn: this is a warning message')
console.error('browser error: this is an error message')
console.debug('browser debug: this is a debug message')
}, [])
return <p>Browser Log Forwarding Test</p>
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('browser-log-forwarding error level', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should only forward error logs to terminal', async () => {
const outputIndex = next.cliOutput.length
await next.browser('/')
await retry(() => {
const output = next.cliOutput.slice(outputIndex)
expect(output).toContain('browser error:')
})
// Get final output after logs are forwarded
const output = next.cliOutput.slice(outputIndex)
// Filter to only browser forwarded logs, excluding hydration noise
const browserLogs = output
.split('\n')
.filter(
(line) =>
line.includes('[browser]') &&
!line.includes('Next.js hydrate callback fire')
)
.join('\n')
expect(browserLogs).toMatchInlineSnapshot(
`"[browser] browser error: this is an error message "`
)
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
browserDebugInfoInTerminal: 'error',
},
}
module.exports = nextConfig
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
import { useEffect } from 'react'
export default function Page() {
useEffect(() => {
console.log('browser log: this is a log message')
console.info('browser info: this is an info message')
console.warn('browser warn: this is a warning message')
console.error('browser error: this is an error message')
console.debug('browser debug: this is a debug message')
}, [])
return <p>Browser Log Forwarding Test</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
browserDebugInfoInTerminal: 'verbose',
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('browser-log-forwarding verbose level', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should forward all logs to terminal', async () => {
const outputIndex = next.cliOutput.length
await next.browser('/')
await retry(() => {
const output = next.cliOutput.slice(outputIndex)
expect(output).toContain('browser error:')
expect(output).toContain('browser warn:')
expect(output).toContain('browser log:')
})
// Get final output after logs are forwarded
const output = next.cliOutput.slice(outputIndex)
// Filter to only browser forwarded logs, excluding noise
const browserLogs = output
.split('\n')
.filter(
(line) =>
line.includes('[browser]') &&
!line.includes('Next.js hydrate callback fire') &&
!line.includes('connected to ws at') &&
!line.includes('received ws message') &&
!line.includes('Download the React DevTools') &&
!line.includes('Next.js page already hydrated')
)
.join('\n')
expect(browserLogs).toMatchInlineSnapshot(`
"[browser] browser log: this is a log message (app/page.tsx:7:13)
[browser] browser info: this is an info message (app/page.tsx:8:13)
[browser] browser warn: this is a warning message (app/page.tsx:9:13)
[browser] browser error: this is an error message
[browser] browser debug: this is a debug message (app/page.tsx:11:13)"
`)
})
})
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
import { useEffect } from 'react'
export default function Page() {
useEffect(() => {
console.log('browser log: this is a log message')
console.info('browser info: this is an info message')
console.warn('browser warn: this is a warning message')
console.error('browser error: this is an error message')
console.debug('browser debug: this is a debug message')
}, [])
return <p>Browser Log Forwarding Test</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
browserDebugInfoInTerminal: 'warn',
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('browser-log-forwarding warn level', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should forward warn and error logs to terminal', async () => {
const outputIndex = next.cliOutput.length
await next.browser('/')
await retry(() => {
const output = next.cliOutput.slice(outputIndex)
expect(output).toContain('browser error:')
expect(output).toContain('browser warn:')
})
// Get final output after logs are forwarded
const output = next.cliOutput.slice(outputIndex)
// Filter to only browser forwarded logs, excluding hydration noise
const browserLogs = output
.split('\n')
.filter(
(line) =>
line.includes('[browser]') &&
!line.includes('Next.js hydrate callback fire')
)
.join('\n')
expect(browserLogs).toMatchInlineSnapshot(`
"[browser] browser warn: this is a warning message (app/page.tsx:9:13)
[browser] browser error: this is an error message "
`)
})
})
......@@ -7,6 +7,14 @@ import {
getRedboxDescription,
getRedboxSource,
} from 'next-test-utils'
// Filter out browser log lines from CLI output to avoid counting forwarded browser errors
function filterBrowserLogs(output: string): string {
return output
.split('\n')
.filter((line) => !line.includes('[browser]'))
.join('\n')
}
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'cache-components-edge-deduplication',
() => {
......@@ -49,7 +57,9 @@ import {
Route segment config "runtime" is not compatible with \`nextConfig.cacheComponents\`. Please remove it."
`)
// Count occurrences of the layout error at the specific location
const layoutErrorMatches = next.cliOutput.match(
// Filter out browser logs to avoid counting forwarded browser errors
const filteredOutput = filterBrowserLogs(next.cliOutput)
const layoutErrorMatches = filteredOutput.match(
/\.\/app\/edge-with-layout\/layout\.tsx:1:14/g
)
// We don't show an error stack, just the individual error messages at each location
......
......@@ -82,6 +82,8 @@ describe('log-file', () => {
if (isNextDev) {
await retry(async () => {
const newLogContent = getNewLogContent()
// The server logs will be replayed in the browser, but they'll not be forwarded to terminal,
// as terminal already has them in the first place.
expect(newLogContent).toMatchInlineSnapshot(`
"[xx:xx:xx.xxx] Server LOG RSC: This is a log message from server component
[xx:xx:xx.xxx] Server ERROR RSC: This is an error message from server component
......@@ -119,10 +121,15 @@ describe('log-file', () => {
if (isNextDev) {
await retry(async () => {
const newLogContent = getNewLogContent()
// Only browser only logs are being forwarded to terminal
expect(newLogContent).toMatchInlineSnapshot(`
"[xx:xx:xx.xxx] Browser LOG Client: Complex circular object: {"data":{"nested":{"items":[1,2,3],"value":42},"parent":"[Circular]"},"metadata":{"name":"safe stringify","version":"1.0.0"},"name":"test"}
[xx:xx:xx.xxx] Browser ERROR Client: This is an error message from client component
[xx:xx:xx.xxx] Browser WARN Client: This is a warning message from client component
[xx:xx:xx.xxx] Server ERROR [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)"
[xx:xx:xx.xxx] Browser ERROR 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)"
[xx:xx:xx.xxx] Server WARN [browser] "Client: This is a warning message from client component" "(app/client/page.tsx:26:13)"
[xx:xx:xx.xxx] Browser WARN Client: This is a warning message from client component
"
`)
})
......
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