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 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 | 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 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 74x 74x 74x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 104x 104x 104x 104x 104x 104x 104x 104x 1x 1x 1x 1x 1x 104x 104x 104x 104x 104x 30x 104x 74x 74x 74x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 1x 1x 1x 1x 1x 58x 58x 1x 1x 1x 1x 1x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 34x 34x 34x 34x 34x 34x 55x 55x 55x 1x 1x 1x 1x 1x 55x 55x 55x 55x 55x 55x 55x 38x 38x 55x 1x 1x 1x 1x 1x 58x 58x 58x 58x 58x 58x 55x 55x 55x 55x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 17x 17x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 37x 37x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 103x 51x 51x 51x 51x 51x 51x 51x 51x 51x 103x 20x 20x 20x 20x 1x 1x 1x 80x 31x 31x 103x 103x 1x 1x 1x 1x 1x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 23x 26x 1x 1x 32x 29x 29x 29x 32x 1x 1x 1x 1x 1x 10x 10x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 36x 34x 34x 34x 36x 36x 36x 1x 1x 1x 1x 1x 1x 1x | 'use client';
/**
* Client-Side Logger
*
* Browser-compatible logger that buffers logs and ships them to the server.
* Designed for capturing client-side errors and events.
*
* Features:
* - Automatic log buffering and batching
* - Flush on page unload
* - Immediate flush on errors
* - Session and page context
*
* @example
* ```typescript
* import { clientLogger } from '@/lib/logging/clientLogger';
*
* // Log user action
* clientLogger.info('User clicked checkout', { cartTotal: 99.99 });
*
* // Log client-side error
* try {
* riskyOperation();
* } catch (error) {
* clientLogger.error('Operation failed', error);
* }
* ```
*/
export type ClientLogLevel = 'debug' | 'info' | 'warn' | 'error';
export interface ClientLogEntry {
level: ClientLogLevel;
message: string;
data?: Record<string, unknown>;
timestamp: string;
url: string;
userAgent: string;
sessionId?: string;
error?: {
name: string;
message: string;
stack?: string;
};
}
export interface ClientLoggerConfig {
/** API endpoint to ship logs to */
endpoint: string;
/** Flush interval in milliseconds */
flushInterval: number;
/** Maximum buffer size before forced flush */
maxBufferSize: number;
/** Minimum log level to capture */
minLevel: ClientLogLevel;
/** Enable console output in development */
consoleOutput: boolean;
}
const DEFAULT_CONFIG: ClientLoggerConfig = {
endpoint: '/api/monitoring/client-logs',
flushInterval: 5000,
maxBufferSize: 10,
minLevel: 'info',
consoleOutput: process.env.NODE_ENV === 'development',
};
const LOG_LEVEL_PRIORITY: Record<ClientLogLevel, number> = {
debug: 0,
info: 1,
warn: 2,
error: 3,
};
/**
* Generate a simple session ID for client-side tracking
*/
function generateSessionId(): string {
return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
/**
* Client Logger Class
*/
class ClientLogger {
private buffer: ClientLogEntry[] = [];
private config: ClientLoggerConfig;
private sessionId: string;
private flushTimer: ReturnType<typeof setInterval> | null = null;
private isInitialized = false;
constructor(config: Partial<ClientLoggerConfig> = {}) {
this.config = { ...DEFAULT_CONFIG, ...config };
this.sessionId = '';
// Only initialize in browser environment
if (typeof window !== 'undefined') {
this.initialize();
}
}
/**
* Initialize the client logger
*/
private initialize(): void {
if (this.isInitialized) return;
// Generate or retrieve session ID
const storedSessionId = sessionStorage.getItem('log_session_id');
if (storedSessionId) {
this.sessionId = storedSessionId;
} else {
this.sessionId = generateSessionId();
sessionStorage.setItem('log_session_id', this.sessionId);
}
// Set up periodic flushing
this.flushTimer = setInterval(() => this.flush(), this.config.flushInterval);
// Flush on page unload
window.addEventListener('beforeunload', () => this.flush());
// Capture unhandled errors
window.addEventListener('error', (event) => {
this.error('Unhandled error', event.error || new Error(event.message), {
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
});
});
// Capture unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
this.error('Unhandled promise rejection', event.reason instanceof Error ? event.reason : new Error(String(event.reason)));
});
this.isInitialized = true;
}
/**
* Check if a log level should be captured
*/
private shouldLog(level: ClientLogLevel): boolean {
return LOG_LEVEL_PRIORITY[level] >= LOG_LEVEL_PRIORITY[this.config.minLevel];
}
/**
* Create a log entry
*/
private createEntry(
level: ClientLogLevel,
message: string,
data?: Record<string, unknown>,
error?: Error
): ClientLogEntry {
const entry: ClientLogEntry = {
level,
message,
data,
timestamp: new Date().toISOString(),
url: typeof window !== 'undefined' ? window.location.href : '',
userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : '',
sessionId: this.sessionId,
};
if (error) {
entry.error = {
name: error.name,
message: error.message,
stack: error.stack,
};
}
return entry;
}
/**
* Add entry to buffer and check if flush is needed
*/
private addToBuffer(entry: ClientLogEntry): void {
this.buffer.push(entry);
// Output to console in development
if (this.config.consoleOutput) {
const consoleMethod = entry.level === 'error' ? 'error' : entry.level === 'warn' ? 'warn' : 'log';
console[consoleMethod](`[${entry.level.toUpperCase()}] ${entry.message}`, entry.data || '');
}
// Immediate flush on error or buffer full
if (entry.level === 'error' || this.buffer.length >= this.config.maxBufferSize) {
this.flush();
}
}
/**
* Core logging method
*/
private log(
level: ClientLogLevel,
message: string,
data?: Record<string, unknown>,
error?: Error
): void {
if (!this.shouldLog(level)) return;
const entry = this.createEntry(level, message, data, error);
this.addToBuffer(entry);
}
// ============================================================================
// Public Logging Methods
// ============================================================================
/**
* Log at debug level
*/
debug(message: string, data?: Record<string, unknown>): void {
this.log('debug', message, data);
}
/**
* Log at info level
*/
info(message: string, data?: Record<string, unknown>): void {
this.log('info', message, data);
}
/**
* Log at warn level
*/
warn(message: string, data?: Record<string, unknown>): void {
this.log('warn', message, data);
}
/**
* Log at error level
*/
error(message: string, error?: Error, data?: Record<string, unknown>): void {
this.log('error', message, data, error);
}
// ============================================================================
// Specialized Methods
// ============================================================================
/**
* Log a user action
*/
action(action: string, data?: Record<string, unknown>): void {
this.info(`User Action: ${action}`, {
type: 'user_action',
action,
...data,
});
}
/**
* Log a page view
*/
pageView(pageName: string, data?: Record<string, unknown>): void {
this.info(`Page View: ${pageName}`, {
type: 'page_view',
pageName,
referrer: typeof document !== 'undefined' ? document.referrer : undefined,
...data,
});
}
/**
* Log a performance metric
*/
metric(name: string, value: number, unit: string): void {
this.info(`Metric: ${name}`, {
type: 'performance_metric',
name,
value,
unit,
});
}
/**
* Log a component error (for error boundaries)
*/
componentError(
componentName: string,
error: Error,
componentStack?: string
): void {
this.error(`Component Error: ${componentName}`, error, {
type: 'component_error',
componentName,
componentStack,
});
}
// ============================================================================
// Buffer Management
// ============================================================================
/**
* Flush the log buffer to the server
*/
async flush(): Promise<void> {
if (this.buffer.length === 0) return;
// Take current buffer and clear it
const entries = [...this.buffer];
this.buffer = [];
try {
// Use sendBeacon for reliability during page unload
const payload = JSON.stringify({ entries });
if (typeof navigator !== 'undefined' && 'sendBeacon' in navigator) {
const blob = new Blob([payload], { type: 'application/json' });
const sent = navigator.sendBeacon(this.config.endpoint, blob);
if (!sent) {
// Fallback to fetch if sendBeacon fails
await this.sendViaFetch(entries, payload);
}
} else {
await this.sendViaFetch(entries, payload);
}
} catch {
// Re-add entries to buffer on failure
this.buffer.unshift(...entries);
}
}
/**
* Send logs via fetch API
*/
private async sendViaFetch(
entries: ClientLogEntry[],
payload: string
): Promise<void> {
try {
const response = await fetch(this.config.endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: payload,
keepalive: true,
});
if (!response.ok) {
throw new Error(`Log shipping failed: ${response.status}`);
}
} catch {
// Re-add entries on failure
this.buffer.unshift(...entries);
}
}
/**
* Get current buffer size
*/
getBufferSize(): number {
return this.buffer.length;
}
/**
* Get session ID
*/
getSessionId(): string {
return this.sessionId;
}
/**
* Update configuration
*/
configure(config: Partial<ClientLoggerConfig>): void {
this.config = { ...this.config, ...config };
// Reset flush timer if interval changed
if (config.flushInterval && this.flushTimer) {
clearInterval(this.flushTimer);
this.flushTimer = setInterval(() => this.flush(), this.config.flushInterval);
}
}
/**
* Destroy the logger and clean up
*/
destroy(): void {
if (this.flushTimer) {
clearInterval(this.flushTimer);
this.flushTimer = null;
}
this.flush();
this.isInitialized = false;
}
}
// Export singleton instance
export const clientLogger = new ClientLogger();
// Export class for custom instances
export { ClientLogger };
|