All files / src logger.js

81.81% Statements 36/44
78.12% Branches 25/32
100% Functions 11/11
80.48% Lines 33/41

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        3x 3x         48x                 48x                 48x 48x 48x     48x                 48x     48x       48x   3x 3x                                     34x     34x     29x 29x   29x                                         29x 29x             29x             30x                                         4x       20x       3x       5x       2x             27x 1x   27x 1x                 41x     3x      
/**
 * Structured logger with OpenTelemetry context
 */
 
const api = require('@opentelemetry/api');
const amqp = require('amqplib');
 
class TelemetryLogger {
  constructor(config = {}) {
    // Default config with deep merge for rabbitmq
    const defaultConfig = {
      mode: 'off',
      logLevel: 'INFO',
      rabbitmq: {
        url: 'amqp://localhost:5672',
        exchange: 'telemetry.exchange'
      }
    };
 
    this.config = {
      ...defaultConfig,
      ...config,
      rabbitmq: {
        ...defaultConfig.rabbitmq,
        ...(config.rabbitmq || {})
      }
    };
 
    this.connection = null;
    this.channel = null;
    this.connected = false;
 
    // Log levels
    this.levels = {
      DEBUG: 5,
      INFO: 9,
      WARN: 13,
      ERROR: 17,
      FATAL: 21
    };
 
    // Current log level
    this.currentLevel = this.levels[this.config.logLevel] || this.levels.INFO;
 
    // Connect to RabbitMQ for log export
    this.connect();
  }
 
  async connect() {
    if (this.config.mode === 'off') return;
 
    try {
      this.connection = await amqp.connect(this.config.rabbitmq.url);
      this.channel = await this.connection.createChannel();
 
      await this.channel.assertExchange(
        this.config.rabbitmq.exchange,
        'topic',
        { durable: true }
      );
 
      this.connected = true;
    } catch (error) {
      console.error('[Logger] Failed to connect to RabbitMQ:', error.message);
    }
  }
 
  /**
   * Core logging method
   */
  log(level, message, data = {}) {
    const levelValue = this.levels[level.toUpperCase()] || this.levels.INFO;
 
    // Check log level
    if (levelValue < this.currentLevel) return;
 
    // Get OpenTelemetry context
    const span = api.trace.getActiveSpan();
    const spanContext = span ? span.spanContext() : null;
 
    const logEntry = {
      timestamp: new Date().toISOString(),
      service_name: this.config.serviceName,
      severity_text: level.toUpperCase(),
      severity_number: levelValue,
      body: { message },
      trace_id: spanContext ? spanContext.traceId : null,
      span_id: spanContext ? spanContext.spanId : null,
      resource_attributes: {
        'service.name': this.config.serviceName,
        'service.version': this.config.serviceVersion,
        'deployment.environment': this.config.environment
      },
      log_attributes: {
        ...data,
        'process.pid': process.pid,
        'host.name': require('os').hostname()
      }
    };
 
    // Log to console
    const consoleMethod = level === 'error' || level === 'fatal' ? 'error' : 'log';
    console[consoleMethod](
      `[${level.toUpperCase()}] ${message}`,
      spanContext ? `[trace:${spanContext.traceId}]` : '',
      data
    );
 
    // Send to RabbitMQ
    this.sendToRabbitMQ(logEntry);
  }
 
  /**
   * Send log to RabbitMQ
   */
  sendToRabbitMQ(logEntry) {
    Eif (!this.connected || !this.channel) return;
 
    try {
      const routingKey = `telemetry.logs.${this.config.serviceName}`;
      const message = Buffer.from(JSON.stringify(logEntry));
 
      this.channel.publish(
        this.config.rabbitmq.exchange,
        routingKey,
        message,
        { persistent: true }
      );
    } catch (error) {
      // Silently fail - don't log to avoid infinite loop
    }
  }
 
  /**
   * Convenience methods
   */
  debug(message, data) {
    this.log('debug', message, data);
  }
 
  info(message, data) {
    this.log('info', message, data);
  }
 
  warn(message, data) {
    this.log('warn', message, data);
  }
 
  error(message, data) {
    this.log('error', message, data);
  }
 
  fatal(message, data) {
    this.log('fatal', message, data);
  }
 
  /**
   * Close logger connection
   */
  async close() {
    if (this.channel) {
      await this.channel.close();
    }
    if (this.connection) {
      await this.connection.close();
    }
  }
}
 
/**
 * Create logger instance
 */
function createLogger(config) {
  return new TelemetryLogger(config);
}
 
module.exports = {
  TelemetryLogger,
  createLogger
};