Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 4x 4x | /**
* Request Context for Logging
*
* Provides utilities for creating request-scoped loggers with
* correlation IDs and request metadata.
*
* @example
* ```typescript
* import { withRequestLogging } from '@/lib/logging/requestContext';
* import { withErrorHandling } from '@/lib/error-handler';
*
* export const POST = withErrorHandling(
* withRequestLogging(async (request, logger) => {
* logger.info('Creating order');
* const order = await createOrder(data);
* logger.info('Order created', { orderId: order.id });
* return successResponse({ order });
* })
* );
* ```
*/
import { v4 as uuidv4 } from 'uuid';
import { logger, Logger, type LogContext } from './logger';
import { NextResponse } from 'next/server';
/**
* Request metadata extracted from the request object
*/
export interface RequestMetadata {
requestId: string;
path: string;
method: string;
userAgent?: string;
ip?: string;
userId?: string | number;
}
/**
* Extract metadata from a request object
*/
export function extractRequestMetadata(
request: Request,
userId?: string | number
): RequestMetadata {
// Try to get request ID from header, or generate one
const requestId =
request.headers.get('x-request-id') ||
request.headers.get('x-correlation-id') ||
uuidv4();
const url = new URL(request.url);
// Extract IP from various headers
const ip =
request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ||
request.headers.get('x-real-ip') ||
undefined;
return {
requestId,
path: url.pathname,
method: request.method,
userAgent: request.headers.get('user-agent') || undefined,
ip,
userId,
};
}
/**
* Create a logger configured for a specific request
*
* @example
* ```typescript
* export async function POST(request: Request) {
* const log = createRequestLogger(request);
* log.info('Processing order');
* // ...
* }
* ```
*/
export function createRequestLogger(
request: Request,
userId?: string | number
): Logger {
const metadata = extractRequestMetadata(request, userId);
return logger.withContext(metadata as LogContext);
}
/**
* Higher-order function that wraps an API handler with request logging
*
* Automatically logs request start/end with duration and provides
* a request-scoped logger to the handler.
*
* @example
* ```typescript
* export const GET = withRequestLogging(async (request, logger) => {
* logger.info('Fetching products');
* const products = await getProducts();
* return Response.json({ products });
* });
* ```
*/
export function withRequestLogging<T extends Response | NextResponse>(
handler: (request: Request, logger: Logger) => Promise<T>
): (request: Request) => Promise<T> {
return async (request: Request): Promise<T> => {
const requestLogger = createRequestLogger(request);
const startTime = performance.now();
requestLogger.info('Request started');
try {
const result = await handler(request, requestLogger);
const durationMs = Number((performance.now() - startTime).toFixed(2));
// Extract status from response
const status = result instanceof Response ? result.status : 200;
requestLogger.request(
request.method,
new URL(request.url).pathname,
status,
durationMs
);
return result;
} catch (error) {
const durationMs = Number((performance.now() - startTime).toFixed(2));
requestLogger.error('Request failed', error as Error, {
durationMs,
});
throw error;
}
};
}
/**
* Add request ID to response headers for client-side correlation
*/
export function addCorrelationHeaders(
response: Response,
requestId: string
): Response {
const newHeaders = new Headers(response.headers);
newHeaders.set('x-request-id', requestId);
newHeaders.set('x-correlation-id', requestId);
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders,
});
}
/**
* Middleware-style wrapper that adds correlation headers to responses
*
* @example
* ```typescript
* export const GET = withCorrelation(async (request, requestId) => {
* // requestId is available for logging
* return Response.json({ data });
* // x-request-id header is automatically added to response
* });
* ```
*/
export function withCorrelation<T extends Response | NextResponse>(
handler: (request: Request, requestId: string) => Promise<T>
): (request: Request) => Promise<Response> {
return async (request: Request): Promise<Response> => {
const requestId =
request.headers.get('x-request-id') ||
request.headers.get('x-correlation-id') ||
uuidv4();
const response = await handler(request, requestId);
// Add correlation headers to response
return addCorrelationHeaders(response, requestId);
};
}
/**
* Combine request logging with correlation headers
*
* @example
* ```typescript
* export const POST = withRequestContext(async (request, { logger, requestId }) => {
* logger.info('Processing');
* return Response.json({ requestId });
* });
* ```
*/
export function withRequestContext<T extends Response | NextResponse>(
handler: (
request: Request,
context: { logger: Logger; requestId: string }
) => Promise<T>
): (request: Request) => Promise<Response> {
return async (request: Request): Promise<Response> => {
const requestId =
request.headers.get('x-request-id') ||
request.headers.get('x-correlation-id') ||
uuidv4();
const requestLogger = logger.withContext({
requestId,
path: new URL(request.url).pathname,
method: request.method,
userAgent: request.headers.get('user-agent') || undefined,
});
const startTime = performance.now();
requestLogger.info('Request started');
try {
const response = await handler(request, {
logger: requestLogger,
requestId,
});
const durationMs = Number((performance.now() - startTime).toFixed(2));
const status = response instanceof Response ? response.status : 200;
requestLogger.request(
request.method,
new URL(request.url).pathname,
status,
durationMs,
{ requestId }
);
return addCorrelationHeaders(response, requestId);
} catch (error) {
const durationMs = Number((performance.now() - startTime).toFixed(2));
requestLogger.error('Request failed', error as Error, { durationMs });
throw error;
}
};
}
|