File size: 6,356 Bytes
b91e262 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 | import { hrtimeBigIntDurationToString } from '../../build/duration-to-string'
import {
blue,
bold,
gray,
green,
red,
white,
yellow,
dim,
} 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'
/**
* Returns true if the incoming request should be ignored for logging.
*/
export function ignoreLoggingIncomingRequests(
request: NodeNextRequest,
loggingConfig: LoggingConfig | undefined
): boolean {
// If it's boolean use the boolean value
if (typeof loggingConfig?.incomingRequests === 'boolean') {
return !loggingConfig.incomingRequests
}
// Any of the value on the chain is falsy, will not ignore the request.
const ignore = loggingConfig?.incomingRequests?.ignore
// If ignore is not set, don't ignore anything
if (!ignore) {
return false
}
// If array of RegExp, ignore if any pattern matches
return ignore.some((pattern) => pattern.test(request.url))
}
export function logRequests(
request: NodeNextRequest,
response: NodeNextResponse,
loggingConfig: LoggingConfig,
requestStartTime: bigint,
requestEndTime: bigint,
devRequestTimingMiddlewareStart: bigint | undefined,
devRequestTimingMiddlewareEnd: bigint | undefined,
devRequestTimingInternalsEnd: bigint | undefined,
devGenerateStaticParamsDuration: bigint | undefined
): void {
if (!ignoreLoggingIncomingRequests(request, loggingConfig)) {
logIncomingRequests(
request,
requestStartTime,
requestEndTime,
response.statusCode,
devRequestTimingMiddlewareStart,
devRequestTimingMiddlewareEnd,
devRequestTimingInternalsEnd,
devGenerateStaticParamsDuration
)
}
if (request.fetchMetrics) {
for (const fetchMetric of request.fetchMetrics) {
logFetchMetric(fetchMetric, loggingConfig)
}
}
}
function logIncomingRequests(
request: NodeNextRequest,
requestStartTime: bigint,
requestEndTime: bigint,
statusCode: number,
devRequestTimingMiddlewareStart: bigint | undefined,
devRequestTimingMiddlewareEnd: bigint | undefined,
devRequestTimingInternalsEnd: bigint | undefined,
devGenerateStaticParamsDuration: bigint | undefined
): void {
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())
const totalRequestTime = requestEndTime - requestStartTime
const times: Array<[label: string, time: bigint]> = []
let middlewareTime: bigint | undefined
if (devRequestTimingMiddlewareStart && devRequestTimingMiddlewareEnd) {
middlewareTime =
devRequestTimingMiddlewareEnd - devRequestTimingMiddlewareStart
times.push(['proxy.ts', middlewareTime])
}
if (devRequestTimingInternalsEnd) {
let frameworkTime = devRequestTimingInternalsEnd - requestStartTime
/* Middleware runs during the internals so we have to subtract it from the framework time */
if (middlewareTime) {
frameworkTime -= middlewareTime
}
// Insert as the first item to be rendered in the list
times.unshift(['compile', frameworkTime])
// Insert after compile, before render based on the execution order.
if (devGenerateStaticParamsDuration) {
// Pages Router getStaticPaths are technically "generate params" as well.
times.push(['generate-params', devGenerateStaticParamsDuration])
}
times.push(['render', requestEndTime - devRequestTimingInternalsEnd])
}
return writeLine(
`${request.method} ${url} ${coloredStatus} in ${hrtimeBigIntDurationToString(totalRequestTime)}${times.length > 0 ? dim(` (${times.map(([label, time]) => `${label}: ${hrtimeBigIntDurationToString(time)}`).join(', ')})`) : ''}`
)
}
function logFetchMetric(
fetchMetric: FetchMetric,
loggingConfig: LoggingConfig | undefined
): void {
let {
cacheReason,
cacheStatus,
cacheWarning,
end,
method,
start,
status,
url,
} = fetchMetric
if (cacheStatus === 'hmr' && !loggingConfig?.fetches?.hmrRefreshes) {
// Cache hits during HMR refreshes are intentionally not logged, unless
// explicitly enabled in the logging config.
return
}
if (loggingConfig?.fetches) {
if (url.length > 48 && !loggingConfig.fetches.fullUrl) {
url = truncateUrl(url)
}
writeLine(
white(
`${method} ${url} ${status} in ${Math.round(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: FetchMetric['cacheStatus']): string {
switch (cacheStatus) {
case 'hmr':
return green('(HMR cache)')
case 'hit':
return green('(cache hit)')
case 'miss':
case 'skip':
return yellow(`(cache ${cacheStatus})`)
default:
return cacheStatus satisfies never
}
}
|