All files / src/common/utils/logger Logger.ts

25.22% Statements 57/226
50% Branches 6/12
19.23% Functions 5/26
25.22% Lines 57/226

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                        1x 1x 1x 1x 1x                                           8x 8x 8x 8x   8x   8x 8x   8x 8x 8x 8x 8x 8x   8x   8x 8x 8x   8x 8x   8x   8x                           8x 8x   8x   8x   8x 8x 8x 8x   8x       8x       8x               8x       8x                               8x                                   8x                                                                       8x                               8x             8x             8x             8x               8x       8x       8x         8x                         8x                 8x                                                       8x                           8x                 8x               8x     1x      
/**
 * Production-ready logging utility with user context and structured formatting
 *
 * Features:
 * - User ID inclusion in all logs
 * - Log level filtering based on environment
 * - Structured log format with metadata
 * - Performance monitoring
 * - Error tracking with stack traces
 * - Request/response logging
 */
 
export enum LogLevel {
  DEBUG = 0,
  INFO = 1,
  WARN = 2,
  ERROR = 3,
}
 
export interface LogContext {
  userId?: string;
  sessionId?: string;
  requestId?: string;
  component?: string;
  action?: string;
  metadata?: Record<string, any>;
  [key: string]: any; // Allow additional properties for flexible usage
}
 
export interface LogEntry {
  timestamp: string;
  level: LogLevel;
  message: string;
  context: LogContext;
  error?: Error;
  stack?: string;
}
 
class Logger {
  private static instance: Logger;
  private currentContext: LogContext = {};
  private logLevel: LogLevel;
 
  private constructor() {
    // Set log level based on environment
    this.logLevel = this.getEnvironmentLogLevel();
  }
 
  public static getInstance(): Logger {
    if (!Logger.instance) {
      Logger.instance = new Logger();
    }
    return Logger.instance;
  }
 
  private getEnvironmentLogLevel(): LogLevel {
    // Handle environments where import.meta.env is not available (e.g., test environments)
    const env =
      typeof import.meta?.env?.MODE !== 'undefined'
        ? import.meta.env.MODE
        : process.env.NODE_ENV || 'development';
    const level =
      typeof import.meta?.env?.VITE_LOG_LEVEL !== 'undefined'
        ? import.meta.env.VITE_LOG_LEVEL
        : process.env.VITE_LOG_LEVEL;
 
    if (level) {
      switch (level.toUpperCase()) {
        case 'DEBUG':
          return LogLevel.DEBUG;
        case 'INFO':
          return LogLevel.INFO;
        case 'WARN':
          return LogLevel.WARN;
        case 'ERROR':
          return LogLevel.ERROR;
      }
    }
 
    // Default levels by environment
    switch (env) {
      case 'development':
        return LogLevel.DEBUG;
      case 'staging':
        return LogLevel.INFO;
      case 'production':
        return LogLevel.WARN;
      default:
        return LogLevel.INFO;
    }
  }
 
  public setContext(context: Partial<LogContext>): void {
    this.currentContext = { ...this.currentContext, ...context };
  }
 
  public clearContext(): void {
    this.currentContext = {};
  }
 
  public setUserId(userId: string | null): void {
    if (userId) {
      this.currentContext.userId = userId;
    } else {
      delete this.currentContext.userId;
    }
  }
 
  private shouldLog(level: LogLevel): boolean {
    return level >= this.logLevel;
  }
 
  private formatMessage(level: LogLevel, message: string, context: LogContext): string {
    const timestamp = new Date().toISOString();
    const levelName = LogLevel[level];
 
    // Build prefix with user ID if available
    const userIdPrefix = context.userId ? `[user id] {${context.userId}}` : '[user id] {anonymous}';
 
    // Build component context
    const componentPrefix = context.component ? `[${context.component}]` : '';
 
    // Build action context
    const actionPrefix = context.action ? `[${context.action}]` : '';
 
    return `${timestamp} ${levelName} ${userIdPrefix} ${componentPrefix}${actionPrefix} ${message}`;
  }
 
  private createLogEntry(
    level: LogLevel,
    message: string,
    context: LogContext,
    error?: Error
  ): LogEntry {
    const mergedContext = { ...this.currentContext, ...context };
 
    return {
      timestamp: new Date().toISOString(),
      level,
      message,
      context: mergedContext,
      error,
      stack: error?.stack,
    };
  }
 
  private outputLog(entry: LogEntry): void {
    const formattedMessage = this.formatMessage(entry.level, entry.message, entry.context);
 
    // Add metadata if present
    const metadata = entry.context.metadata;
    const metadataStr = metadata ? ` | Metadata: ${JSON.stringify(metadata)}` : '';
 
    const fullMessage = formattedMessage + metadataStr;
 
    switch (entry.level) {
      case LogLevel.DEBUG:
        console.debug(fullMessage);
        break;
      case LogLevel.INFO:
        console.info(fullMessage);
        break;
      case LogLevel.WARN:
        console.warn(fullMessage);
        if (entry.error) console.warn(entry.error);
        break;
      case LogLevel.ERROR:
        console.error(fullMessage);
        if (entry.error) console.error(entry.error);
        break;
    }
 
    // In production, you might want to send logs to an external service
    const isProd =
      typeof import.meta?.env?.MODE !== 'undefined'
        ? import.meta.env.MODE === 'production'
        : process.env.NODE_ENV === 'production';
    if (isProd && entry.level >= LogLevel.ERROR) {
      this.sendToExternalService();
    }
  }
 
  private sendToExternalService(): void {
    // Placeholder for external logging service integration
    // This could be Sentry, LogRocket, DataDog, etc.
    try {
      // Example: Send to external service
      // await fetch('/api/logs', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify(entry)
      // });
    } catch (error) {
      // Fallback to console if external service fails
      console.error('Failed to send log to external service:', error);
    }
  }
 
  public debug(message: string, context: LogContext = {}): void {
    if (!this.shouldLog(LogLevel.DEBUG)) return;
 
    const entry = this.createLogEntry(LogLevel.DEBUG, message, context);
    this.outputLog(entry);
  }
 
  public info(message: string, context: LogContext = {}): void {
    if (!this.shouldLog(LogLevel.INFO)) return;
 
    const entry = this.createLogEntry(LogLevel.INFO, message, context);
    this.outputLog(entry);
  }
 
  public warn(message: string, context: LogContext = {}, error?: Error): void {
    if (!this.shouldLog(LogLevel.WARN)) return;
 
    const entry = this.createLogEntry(LogLevel.WARN, message, context, error);
    this.outputLog(entry);
  }
 
  public error(message: string, context: LogContext = {}, error?: Error): void {
    if (!this.shouldLog(LogLevel.ERROR)) return;
 
    const entry = this.createLogEntry(LogLevel.ERROR, message, context, error);
    this.outputLog(entry);
  }
 
  // Specialized logging methods for common use cases
  public auth(message: string, context: LogContext = {}): void {
    this.info(message, { ...context, component: 'Auth' });
  }
 
  public api(message: string, context: LogContext = {}): void {
    this.info(message, { ...context, component: 'API' });
  }
 
  public ui(message: string, context: LogContext = {}): void {
    this.debug(message, { ...context, component: 'UI' });
  }
 
  // Performance monitoring
  public startTimer(timerName: string): () => void {
    const start = performance.now();
 
    return () => {
      const duration = performance.now() - start;
      this.info(`${timerName} completed`, {
        component: 'Performance',
        metadata: { duration: `${duration.toFixed(2)}ms` },
      });
    };
  }
 
  // API request/response logging
  public logApiRequest(url: string, method: string, context: LogContext = {}): void {
    this.debug(`API Request: ${method} ${url}`, {
      ...context,
      component: 'API',
      action: 'request',
      metadata: { url, method },
    });
  }
 
  public logApiResponse(
    url: string,
    method: string,
    status: number,
    duration: number,
    context: LogContext = {}
  ): void {
    const level = status >= 400 ? LogLevel.WARN : LogLevel.DEBUG;
    const message = `API Response: ${method} ${url} - ${status} (${duration.toFixed(2)}ms)`;
 
    if (level === LogLevel.WARN) {
      this.warn(message, {
        ...context,
        component: 'API',
        action: 'response',
        metadata: { url, method, status, duration },
      });
    } else {
      this.debug(message, {
        ...context,
        component: 'API',
        action: 'response',
        metadata: { url, method, status, duration },
      });
    }
  }
 
  // Error boundary logging
  public logComponentError(componentName: string, error: Error, context: LogContext = {}): void {
    this.error(
      `Component error in ${componentName}`,
      {
        ...context,
        component: componentName,
        action: 'render_error',
        metadata: { errorName: error.name, errorMessage: error.message },
      },
      error
    );
  }
 
  // User action logging
  public logUserAction(action: string, context: LogContext = {}): void {
    this.info(`User action: ${action}`, {
      ...context,
      component: 'UserAction',
      action,
    });
  }
 
  // Navigation logging
  public logNavigation(from: string, to: string, context: LogContext = {}): void {
    this.debug(`Navigation: ${from} -> ${to}`, {
      ...context,
      component: 'Navigation',
      action: 'route_change',
      metadata: { from, to },
    });
  }
}
 
// Export singleton instance
export const logger = Logger.getInstance();
 
// Types are already exported via export interface above