All files / src/utils logger.ts

0% Statements 0/87
0% Branches 0/110
0% Functions 0/15
0% Lines 0/80

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { inspect } from 'util';
 
interface LogContext {
  requestId?: string;
  userId?: string;
  error?: any;
  request?: any;
  response?: any;
  duration?: number;
  [key: string]: any;
}
 
export class Logger {
  private static getLogLevel(): string {
    return process.env.LOG_LEVEL || (process.env.NODE_ENV === 'development' ? 'debug' : 'info');
  }
 
  private static shouldLog(level: string): boolean {
    const currentLevel = this.getLogLevel().toLowerCase();
    const levels = ['error', 'warn', 'info', 'debug'];
    const currentIndex = levels.indexOf(currentLevel);
    const messageIndex = levels.indexOf(level.toLowerCase());
    
    return messageIndex <= currentIndex;
  }
 
  private static formatMessage(level: string, message: string, context?: LogContext): string {
    const timestamp = new Date().toISOString();
    const isDevelopment = process.env.NODE_ENV === 'development';
    const supportsColors = this.supportsColors();
    
    // Create a more readable header with level, timestamp, and message
    const levelSymbol = this.getLevelSymbol(level);
    const levelColor = this.getLevelColor(level, isDevelopment && supportsColors);
    const timestampFormatted = (isDevelopment && supportsColors) ? 
      `\x1b[90m${timestamp}\x1b[0m` : // Gray timestamp in dev
      timestamp;
    
    const header = (isDevelopment && supportsColors) ?
      `${levelColor}${levelSymbol} [${level}]\x1b[0m ${timestampFormatted} \x1b[1m${message}\x1b[0m` :
      `${levelSymbol} [${level}] ${timestamp} ${message}`;
    
    // Format context data if present
    if (context && Object.keys(context).length > 0) {
      const contextFormatted = inspect(context, {
        depth: isDevelopment ? 10 : 6, // Much deeper inspection
        colors: isDevelopment && supportsColors,
        compact: false,
        breakLength: 100,
        maxArrayLength: isDevelopment ? 20 : 10, // Show more array elements
        maxStringLength: isDevelopment ? 500 : 200, // Longer strings
        showHidden: false,
        sorted: true,
        getters: false,
        showProxy: false, // Don't show proxy details
        customInspect: true // Use custom inspect methods
      });
      
      // Add visual separation
      const separator = (isDevelopment && supportsColors) ? 
        `\x1b[90m${'─'.repeat(80)}\x1b[0m` : 
        '─'.repeat(80);
      
      return `${header}\n${separator}\n${contextFormatted}`;
    }
    
    return header;
  }
 
  private static supportsColors(): boolean {
    // Check if colors are explicitly disabled
    if (process.env.FORCE_COLOR === '0') return false;
    if (process.env.NO_COLOR) return false;
    if (process.env.TERM === 'dumb') return false;
    
    // Check if colors are explicitly enabled
    if (process.env.FORCE_COLOR === '1' || process.env.FORCE_COLOR === '2' || process.env.FORCE_COLOR === '3') return true;
    
    // Check if we're in a TTY
    if (process.stdout && !process.stdout.isTTY) return false;
    
    // Check terminal capabilities - be more permissive
    if (process.env.TERM && (
      process.env.TERM.includes('256color') ||
      process.env.TERM.includes('truecolor') ||
      process.env.TERM.includes('xterm') ||
      process.env.TERM.includes('screen') ||
      process.env.TERM.includes('tmux') ||
      process.env.TERM.includes('color')
    )) return true;
    
    // Check COLORTERM
    if (process.env.COLORTERM) return true;
    
    // Default to true for development mode if we have a TTY
    return process.env.NODE_ENV === 'development' && process.stdout.isTTY;
  }
 
  private static getLevelSymbol(level: string): string {
    const symbols = {
      'INFO': 'â„šī¸ ',
      'DEBUG': '🐛',
      'WARN': 'âš ī¸ ',
      'ERROR': '❌'
    };
    return symbols[level as keyof typeof symbols] || '📝';
  }
 
  private static getLevelPrefix(level: string, supportsColors: boolean): string {
    if (supportsColors) {
      return '';
    }
    
    // Provide visual distinction without colors
    const prefixes = {
      'ERROR': '>>> ',
      'WARN': '>>> ',
      'INFO': '>>> ',
      'DEBUG': '>>> '
    };
    return prefixes[level as keyof typeof prefixes] || '>>> ';
  }
 
  private static getLevelColor(level: string, isDevelopment: boolean): string {
    if (!isDevelopment) return '';
    
    const colors = {
      'INFO': '\x1b[36m',    // Cyan
      'DEBUG': '\x1b[35m',   // Magenta
      'WARN': '\x1b[33m',    // Yellow
      'ERROR': '\x1b[31m'    // Red
    };
    return colors[level as keyof typeof colors] || '\x1b[37m'; // White default
  }
 
  static info(message: string, context?: LogContext): void {
    if (this.shouldLog('info')) {
      console.log(this.formatMessage('INFO', message, context));
    }
  }
 
  static warn(message: string, context?: LogContext): void {
    if (this.shouldLog('warn')) {
      console.warn(this.formatMessage('WARN', message, context));
    }
  }
 
  static error(message: string, context?: LogContext): void {
    if (this.shouldLog('error')) {
      console.error(this.formatMessage('ERROR', message, context));
    }
  }
 
  static debug(message: string, context?: LogContext): void {
    if (this.shouldLog('debug')) {
      console.debug(this.formatMessage('DEBUG', message, context));
    }
  }
 
  // Enhanced logging methods that automatically detect and format objects
  static logObject(message: string, obj: any, level: 'info' | 'debug' | 'warn' | 'error' = 'info'): void {
    const isDevelopment = process.env.NODE_ENV === 'development';
    const supportsColors = this.supportsColors();
    
    // Create a more readable object representation
    const formattedObj = inspect(obj, {
      depth: isDevelopment ? 10 : 6, // Much deeper inspection
      colors: isDevelopment && supportsColors,
      compact: false, // Always use expanded format for objects
      breakLength: 100,
      maxArrayLength: isDevelopment ? 20 : 10,
      maxStringLength: isDevelopment ? 500 : 200,
      showHidden: false,
      sorted: true,
      getters: false,
      showProxy: false,
      customInspect: true
    });
 
    const context = {
      objectType: obj?.constructor?.name || typeof obj,
      objectSize: JSON.stringify(obj).length,
      formattedObject: formattedObj
    };
 
    switch (level) {
      case 'info':
        this.info(message, context);
        break;
      case 'debug':
        this.debug(message, context);
        break;
      case 'warn':
        this.warn(message, context);
        break;
      case 'error':
        this.error(message, context);
        break;
    }
  }
 
  // Helper for HTTP request logging
  static logRequest(req: any, res: any, duration: number): void {
    const context = {
      requestId: req.headers['x-request-id'],
      request: {
        method: req.method,
        url: req.url,
        userAgent: req.get('User-Agent'),
        ip: req.ip
      },
      response: {
        statusCode: res.statusCode
      },
      duration
    };
 
    if (res.statusCode >= 400) {
      this.error(`HTTP ${req.method} ${req.url} - ${res.statusCode}`, context);
    } else {
      this.info(`HTTP ${req.method} ${req.url} - ${res.statusCode}`, context);
    }
  }
 
  // Helper for service operation logging
  static logServiceOperation(service: string, operation: string, success: boolean, context?: LogContext): void {
    const message = `${service}.${operation} ${success ? 'succeeded' : 'failed'}`;
    const logContext = {
      service,
      operation,
      success,
      ...context
    };
 
    if (success) {
      this.info(message, logContext);
    } else {
      this.error(message, logContext);
    }
  }
 
 
  // Helper for logging API responses with better formatting
  static logApiResponse(operation: string, response: any, level: 'info' | 'debug' | 'warn' | 'error' = 'info'): void {
    const context = {
      operation,
      responseType: response?.constructor?.name || typeof response,
      statusCode: response?.status || response?.statusCode,
      hasData: !!response?.data,
      dataKeys: response?.data ? Object.keys(response.data) : [],
      responseSize: JSON.stringify(response).length
    };
 
    // Add the actual response data for detailed inspection
    if (process.env.NODE_ENV === 'development') {
      context['responseData'] = response;
    }
 
    switch (level) {
      case 'info':
        this.info(`API Response: ${operation}`, context);
        break;
      case 'debug':
        this.debug(`API Response: ${operation}`, context);
        break;
      case 'warn':
        this.warn(`API Response: ${operation}`, context);
        break;
      case 'error':
        this.error(`API Response: ${operation}`, context);
        break;
    }
  }
}