NNext.js 中文网 GitHub

logging

配置在开发模式下运行 Next.js 时终端中的日志行为,包括 fetch 日志、传入请求,以及将浏览器控制台日志转发到终端。

选项#

获取(Fetching)#

你可以配置在开发模式下运行 Next.js 时的日志级别,以及是否将完整 URL 记录到控制台。

next.config.js
module.exports = {
  logging: {
    fetches: {
      fullUrl: true,
    },
  },
}

从 Server Components HMR 缓存恢复的任何 fetch 请求默认不会记录。但是,可以通过将 logging.fetches.hmrRefreshes 设置为 true 来启用。

next.config.js
module.exports = {
  logging: {
    fetches: {
      hmrRefreshes: true,
    },
  },
}

Server Function#

Server Function 调用在开发期间默认会记录。你可以通过将 logging.serverFunctions 设置为 false 来禁用此功能。

next.config.js
module.exports = {
  logging: {
    serverFunctions: false,
  },
}

启用后,终端会显示每个 Server Function 调用的函数名、参数和持续时间:

Terminal
POST /
  └─ ƒ myAction(arg1, arg2) in 5ms app/actions.ts

传入请求#

默认情况下,开发期间所有传入请求都会记录到控制台。你可以使用 incomingRequests 选项决定忽略哪些请求。 由于此功能仅在开发期间记录,因此该选项不会影响生产构建。

next.config.js
module.exports = {
  logging: {
    incomingRequests: {
      ignore: [/\/api\/v1\/health/],
    },
  },
}

或者,你可以通过将 incomingRequests 设置为 false 来禁用传入请求日志记录。

next.config.js
module.exports = {
  logging: {
    incomingRequests: false,
  },
}

浏览器控制台日志#

你可以在开发期间将浏览器控制台日志(如 console.log、console.warn、console.error)转发到终端。这对于调试客户端代码很有用,无需查看浏览器的开发者工具。

next.config.js
module.exports = {
  logging: {
    browserToTerminal: true,
  },
}

选项#

browserToTerminal 选项接受以下值:

值描述
'warn'默认仅转发警告和错误
'error'仅转发错误
true转发所有控制台输出(log、info、warn、error)
false禁用浏览器日志转发
next.config.js
module.exports = {
  logging: {
    browserToTerminal: 'warn',
  },
}

源代码位置#

启用后,浏览器日志默认包含源代码位置信息(文件路径和行号)。例如:

app/page.tsx
'use client'

export default function Home() {
  return (
    <button
      type="button"
      onClick={() => {
        console.log('Hello World')
      }}
    >
      Click me
    </button>
  )
}

点击按钮会将此消息打印到终端:

Terminal
[browser] Hello World (app/page.tsx:8:17)
pages/index.tsx
export default function Home() {
  return (
    <button
      type="button"
      onClick={() => {
        console.log('Hello World')
      }}
    >
      Click me
    </button>
  )
}

点击按钮会将此消息打印到终端:

Terminal
[browser] Hello World (pages/index.tsx:6:17)

禁用日志#

此外,你可以通过将 logging 设置为 false 来禁用开发日志。

next.config.js
module.exports = {
  logging: false,
}

版本历史#

版本变更
v16.2.0新增 browserToTerminal(从 experimental.browserDebugInfoInTerminal 迁移而来)
v15.4.0引入 experimental.browserDebugInfoInTerminal
v15.2.0新增 incomingRequests
v15.0.0新增 logging: false 选项,为 App Router 新增 fetches.hmrRefreshes
v14.0.0logging.fetches 在 App Router 中转为稳定版
Next.js 中文网