Unverified Commit 8520afaf authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Move request logging code out of `NextNodeServer` (#68286)

This moves the dev-only request logging from the `NextNodeServer` into `DevServer`, and also extracts the logging logic into its own module to declutter the server class. It should not contain any behavioral changes.
parent 0a9ef185
......@@ -199,6 +199,12 @@ export interface ReactCompilerOptions {
panicThreshold?: 'ALL_ERRORS' | 'CRITICAL_ERRORS' | 'NONE'
}
export interface LoggingConfig {
fetches?: {
fullUrl?: boolean
}
}
export interface ExperimentalConfig {
appNavFailHandling?: boolean
flyingShuttle?: boolean
......@@ -853,13 +859,7 @@ export interface NextConfig extends Record<string, any> {
}
>
logging?:
| {
fetches?: {
fullUrl?: boolean
}
}
| false
logging?: LoggingConfig | false
/**
* period (in seconds) where the server allow to serve stale cache
......
import {
blue,
bold,
gray,
green,
red,
white,
yellow,
} from '../../lib/picocolors'
import { stripNextRscUnionQuery } from '../../lib/url'
import type { FetchMetric } from '../base-http'
import type { NodeNextRequest, NodeNextResponse } from '../base-http/node'
import type { LoggingConfig } from '../config-shared'
import { getRequestMeta } from '../request-meta'
export interface RequestLoggingOptions {
readonly request: NodeNextRequest
readonly response: NodeNextResponse
readonly loggingConfig: LoggingConfig | undefined
readonly requestDurationInMs: number
}
export function logRequests(options: RequestLoggingOptions): void {
const { request, response, loggingConfig, requestDurationInMs } = options
logIncomingRequest({
request,
requestDurationInMs,
statusCode: response.statusCode,
})
if (request.fetchMetrics) {
for (const fetchMetric of request.fetchMetrics) {
logFetchMetric(fetchMetric, loggingConfig)
}
}
}
interface IncomingRequestOptions {
readonly request: NodeNextRequest
readonly requestDurationInMs: number
readonly statusCode: number
}
function logIncomingRequest(options: IncomingRequestOptions): void {
const { request, requestDurationInMs, statusCode } = options
const isRSC = getRequestMeta(request, 'isRSCRequest')
const url = isRSC ? stripNextRscUnionQuery(request.url) : request.url
const statusCodeColor =
statusCode < 200
? white
: statusCode < 300
? green
: statusCode < 400
? blue
: statusCode < 500
? yellow
: red
const coloredStatus = statusCodeColor(statusCode.toString())
return writeLine(
`${request.method} ${url} ${coloredStatus} in ${requestDurationInMs}ms`
)
}
function logFetchMetric(
fetchMetric: FetchMetric,
loggingConfig: LoggingConfig | undefined
): void {
let {
cacheReason,
cacheStatus,
cacheWarning,
end,
method,
start,
status,
url,
} = fetchMetric
if (cacheStatus === 'hmr') {
// Cache hits during HMR refreshes are intentionally not logged.
return
}
if (loggingConfig?.fetches) {
if (url.length > 48 && !loggingConfig.fetches.fullUrl) {
url = truncateUrl(url)
}
writeLine(
white(
`${method} ${url} ${status} in ${end - start}ms ${formatCacheStatus(cacheStatus)}`
),
1
)
if (cacheStatus === 'skip' || cacheStatus === 'miss') {
writeLine(
gray(
`Cache ${cacheStatus === 'skip' ? 'skipped' : 'missed'} reason: (${white(cacheReason)})`
),
2
)
}
} else if (cacheWarning) {
// When logging for fetches is not enabled, we still want to print any
// associated warnings, so we print the request first to provide context.
writeLine(white(`${method} ${url}`), 1)
}
if (cacheWarning) {
writeLine(`${yellow(bold('⚠'))} ${white(cacheWarning)}`, 2)
}
}
function writeLine(text: string, indentationLevel = 0): void {
process.stdout.write(` ${'│ '.repeat(indentationLevel)}${text}\n`)
}
function truncate(text: string, maxLength: number): string {
return maxLength !== undefined && text.length > maxLength
? text.substring(0, maxLength) + '..'
: text
}
function truncateUrl(url: string): string {
const { protocol, host, pathname, search } = new URL(url)
return (
protocol +
'//' +
truncate(host, 16) +
truncate(pathname, 24) +
truncate(search, 16)
)
}
function formatCacheStatus(cacheStatus: 'hit' | 'miss' | 'skip'): string {
const color = cacheStatus === 'hit' ? green : yellow
return color(`(cache ${cacheStatus})`)
}
import type { FindComponentsResult } from '../next-server'
import type { FindComponentsResult, NodeRequestHandler } from '../next-server'
import type { LoadComponentsReturnType } from '../load-components'
import type { Options as ServerOptions } from '../next-server'
import type { Params } from '../../client/components/params'
......@@ -9,9 +9,10 @@ import type { FallbackMode, MiddlewareRoutingItem } from '../base-server'
import type { FunctionComponent } from 'react'
import type { RouteDefinition } from '../route-definitions/route-definition'
import type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager'
import type {
NextParsedUrlQuery,
NextUrlWithParsedQuery,
import {
getRequestMeta,
type NextParsedUrlQuery,
type NextUrlWithParsedQuery,
} from '../request-meta'
import type { DevBundlerService } from '../lib/dev-bundler-service'
import type { IncrementalCache } from '../lib/incremental-cache'
......@@ -67,6 +68,7 @@ import { buildCustomRoute } from '../../lib/build-custom-route'
import { decorateServerError } from '../../shared/lib/error-source'
import type { ServerOnInstrumentationRequestError } from '../app-render/types'
import type { ServerComponentsHmrCache } from '../response-cache'
import { logRequests } from './log-requests'
// Load ReactDevOverlay only when needed
let ReactDevOverlayImpl: FunctionComponent
......@@ -461,6 +463,43 @@ export default class DevServer extends Server {
}
}
public getRequestHandler(): NodeRequestHandler {
const handler = super.getRequestHandler()
return (req, res, parsedUrl) => {
const request = this.normalizeReq(req)
const response = this.normalizeRes(res)
const loggingConfig = this.nextConfig.logging
if (loggingConfig !== false) {
const start = Date.now()
const isMiddlewareRequest = getRequestMeta(req, 'middlewareInvoke')
if (!isMiddlewareRequest) {
response.originalResponse.once('close', () => {
// NOTE: The route match is only attached to the request's meta data
// after the request handler is created, so we need to check it in the
// close handler and not before.
const routeMatch = getRequestMeta(req).match
if (!routeMatch) {
return
}
logRequests({
request,
response,
loggingConfig,
requestDurationInMs: Date.now() - start,
})
})
}
}
return handler(request, response, parsedUrl)
}
}
public async handleRequest(
req: NodeNextRequest,
res: NodeNextResponse,
......
......@@ -100,7 +100,6 @@ import { interopDefault } from '../lib/interop-default'
import { formatDynamicImportPath } from '../lib/format-dynamic-import-path'
import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'
import { isInterceptionRouteRewrite } from '../lib/generate-interception-routes-rewrites'
import { stripNextRscUnionQuery } from '../lib/url'
import type { ServerOnInstrumentationRequestError } from './app-render/types'
export * from './base-server'
......@@ -118,16 +117,6 @@ const dynamicRequire = process.env.NEXT_MINIMAL
? __non_webpack_require__
: require
function writeStdoutLine(text: string) {
process.stdout.write(' ' + text + '\n')
}
function formatRequestUrl(url: string, maxLength: number | undefined) {
return maxLength !== undefined && url.length > maxLength
? url.substring(0, maxLength) + '..'
: url
}
export type NodeRequestHandler = BaseRequestHandler<
IncomingMessage | NodeNextRequest,
ServerResponse | NodeNextResponse
......@@ -1080,13 +1069,13 @@ export default class NextNodeServer extends BaseServer<
return nodeFs
}
private normalizeReq(
protected normalizeReq(
req: NodeNextRequest | IncomingMessage
): NodeNextRequest {
return !(req instanceof NodeNextRequest) ? new NodeNextRequest(req) : req
}
private normalizeRes(
protected normalizeRes(
res: NodeNextResponse | ServerResponse
): NodeNextResponse {
return !(res instanceof NodeNextResponse) ? new NodeNextResponse(res) : res
......@@ -1106,157 +1095,16 @@ export default class NextNodeServer extends BaseServer<
private makeRequestHandler(): NodeRequestHandler {
// This is just optimization to fire prepare as soon as possible. It will be
// properly awaited later. We add the catch here to ensure that it does not
// cause a unhandled promise rejection. The promise rejection wil be
// cause an unhandled promise rejection. The promise rejection will be
// handled later on via the `await` when the request handler is called.
this.prepare().catch((err) => {
console.error('Failed to prepare server', err)
})
const handler = super.getRequestHandler()
return (req, res, parsedUrl) => {
const normalizedReq = this.normalizeReq(req)
const normalizedRes = this.normalizeRes(res)
const logConfig = this.nextConfig.logging
const isLoggingDisabled = logConfig === false
const fetchesLoggingConfig = isLoggingDisabled
? false
: logConfig?.fetches
const enabledVerboseLogging = !!fetchesLoggingConfig
const shouldTruncateUrl =
typeof fetchesLoggingConfig === 'object' &&
!fetchesLoggingConfig.fullUrl
if (this.renderOpts.dev) {
const { blue, green, yellow, red, gray, white, bold } =
require('../lib/picocolors') as typeof import('../lib/picocolors')
const { originalResponse } = normalizedRes
const reqStart = Date.now()
const isMiddlewareRequest = getRequestMeta(req, 'middlewareInvoke')
const reqCallback = () => {
const fetchMetrics = normalizedReq.fetchMetrics || []
delete normalizedReq.fetchMetrics
if (isLoggingDisabled) return
// we don't log for non-route requests
const routeMatch = getRequestMeta(req).match
if (!routeMatch || isMiddlewareRequest) return
// NOTE: this is only attached after handle has started, this runs
// after the response has been sent, so it should have it set.
const isRSC = getRequestMeta(normalizedReq, 'isRSCRequest')
const reqEnd = Date.now()
const reqDuration = reqEnd - reqStart
const statusColor = (status?: number) => {
if (!status || status < 200) return white
else if (status < 300) return green
else if (status < 400) return blue
else if (status < 500) return yellow
return red
}
const color = statusColor(res.statusCode)
const method = req.method || 'GET'
const requestUrl = req.url || ''
const loggingUrl = isRSC
? stripNextRscUnionQuery(requestUrl)
: requestUrl
const indentation = '│ '
writeStdoutLine(
`${method} ${loggingUrl} ${color(
res.statusCode.toString()
)} in ${reqDuration}ms`
)
for (let i = 0; i < fetchMetrics.length; i++) {
const metric = fetchMetrics[i]
let { cacheStatus, cacheReason, cacheWarning, url } = metric
if (cacheStatus === 'hmr') {
// Cache hits during HMR refreshes are intentionally not logged.
continue
}
if (enabledVerboseLogging) {
let cacheReasonStr = ''
let cacheColor
const duration = metric.end - metric.start
if (cacheStatus === 'hit') {
cacheColor = green
} else {
cacheColor = yellow
const status = cacheStatus === 'skip' ? 'skipped' : 'missed'
cacheReasonStr = gray(
`Cache ${status} reason: (${white(cacheReason)})`
)
}
if (url.length > 48) {
const parsed = new URL(url)
const truncatedHost = formatRequestUrl(
parsed.host,
shouldTruncateUrl ? 16 : undefined
)
const truncatedPath = formatRequestUrl(
parsed.pathname,
shouldTruncateUrl ? 24 : undefined
)
const truncatedSearch = formatRequestUrl(
parsed.search,
shouldTruncateUrl ? 16 : undefined
)
url =
parsed.protocol +
'//' +
truncatedHost +
truncatedPath +
truncatedSearch
}
const status = cacheColor(`(cache ${cacheStatus})`)
writeStdoutLine(
`${indentation}${white(
metric.method
)} ${white(url)} ${metric.status} in ${duration}ms ${status}`
)
if (cacheReasonStr) {
writeStdoutLine(`${indentation}${indentation}${cacheReasonStr}`)
}
if (cacheWarning) {
writeStdoutLine(
`${indentation}${indentation}${yellow(bold('⚠'))} ${white(cacheWarning)}`
)
}
} else if (cacheWarning) {
writeStdoutLine(
`${indentation}${white(metric.method)} ${white(url)}`
)
writeStdoutLine(
`${indentation}${indentation}${yellow(bold('⚠'))} ${white(cacheWarning)}`
)
}
}
originalResponse.off('close', reqCallback)
}
originalResponse.on('close', reqCallback)
}
return handler(normalizedReq, normalizedRes, parsedUrl)
}
return (req, res, parsedUrl) =>
handler(this.normalizeReq(req), this.normalizeRes(res), parsedUrl)
}
public async revalidate({
......
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