CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-insert-koin--koin-core-js

KOIN - Kotlin simple Dependency Injection Framework for JavaScript/Browser platform

Pending
Overview
Eval results
Files

logging-system.mddocs/

Logging System

Configurable logging system with multiple levels, JavaScript console integration, and custom logger support for debugging and monitoring dependency injection operations.

Capabilities

Logger Interface

Abstract logging interface for implementing custom loggers with different output destinations.

/**
 * Abstract logger class for Koin logging system
 */
abstract class Logger {
  /**
   * Display log message at specified level - must be implemented by subclasses
   * @param level - Log level for the message
   * @param message - Log message to display
   */
  abstract display(level: Level, message: string): void;

  /**
   * Log debug level message
   * @param message - Debug message
   */
  debug(message: string): void;

  /**
   * Log info level message
   * @param message - Info message
   */
  info(message: string): void;

  /**
   * Log warning level message
   * @param message - Warning message
   */
  warn(message: string): void;

  /**
   * Log error level message
   * @param message - Error message
   */
  error(message: string): void;

  /**
   * Check if logger is at specified level
   * @param level - Level to check
   * @returns true if logger will output at this level
   */
  isAt(level: Level): boolean;
}

Usage Examples:

import { Logger, Level } from "koin-core";

// Custom file logger implementation
class FileLogger extends Logger {
  constructor(logFilePath) {
    super();
    this.logFilePath = logFilePath;
    this.currentLevel = Level.INFO;
  }
  
  display(level, message) {
    if (this.isAt(level)) {
      const timestamp = new Date().toISOString();
      const logEntry = `[${timestamp}] ${level}: ${message}\n`;
      
      // Write to file (pseudo-code for file operations)
      this.appendToFile(this.logFilePath, logEntry);
    }
  }
  
  isAt(level) {
    const levelPriority = {
      [Level.DEBUG]: 0,
      [Level.INFO]: 1,
      [Level.WARNING]: 2,
      [Level.ERROR]: 3,
      [Level.NONE]: 4
    };
    
    return levelPriority[level] >= levelPriority[this.currentLevel];
  }
}

// Custom network logger
class NetworkLogger extends Logger {
  constructor(endpoint) {
    super();
    this.endpoint = endpoint;
  }
  
  display(level, message) {
    if (level !== Level.NONE) {
      const logData = {
        level: level,
        message: message,
        timestamp: Date.now(),
        source: "koin-core"
      };
      
      // Send to logging service
      fetch(this.endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(logData)
      }).catch(err => console.error("Logging failed:", err));
    }
  }
}

Log Levels

Hierarchical log levels for controlling logging verbosity and filtering.

/**
 * Log levels for controlling output verbosity
 */
enum Level {
  /** Debug level - most verbose, shows all operations */
  DEBUG = "DEBUG",
  
  /** Info level - general information about operations */
  INFO = "INFO",
  
  /** Warning level - potential issues that don't prevent operation */
  WARNING = "WARNING",
  
  /** Error level - errors that may affect operation */
  ERROR = "ERROR",
  
  /** None level - no logging output */
  NONE = "NONE"
}

Usage Examples:

import { startKoin, module, Level } from "koin-core";

const appModule = module((builder) => {
  builder.single(() => new DatabaseService());
  builder.factory(() => new ApiClient());
});

// Configure logging level during application start
startKoin((app) => {
  app.modules([appModule]);
  app.printLogger(Level.DEBUG); // Show all debug information
});

// Or configure with different levels
startKoin((app) => {
  app.modules([appModule]);
  app.printLogger(Level.ERROR); // Only show errors
});

// Production configuration - no logging
startKoin((app) => {
  app.modules([appModule]);
  app.printLogger(Level.NONE); // Disable all logging
});

JavaScript Console Logger

Built-in logger implementation using JavaScript console for web and Node.js environments.

/**
 * Console-based logger implementation for JavaScript environments
 * Uses console.log, console.warn, console.error for output
 */
class PrintLogger extends Logger {
  /**
   * Create console logger with specified level
   * @param level - Log level threshold (default: INFO)
   */
  constructor(level: Level = Level.INFO);

  /**
   * Display message using appropriate console method
   * @param level - Log level for the message
   * @param message - Message to display
   */
  display(level: Level, message: string): void;
}

Usage Examples:

import { PrintLogger, Level, koinApplication } from "koin-core";

// Use console logger directly
const logger = new PrintLogger(Level.DEBUG);
logger.debug("Debug message");      // console.log
logger.info("Info message");        // console.log  
logger.warn("Warning message");     // console.warn
logger.error("Error message");      // console.error

// Configure application with console logger
const app = koinApplication((app) => {
  app.modules([myModule]);
  app.logger(new PrintLogger(Level.INFO));
});

// Or use the convenience method
const app2 = koinApplication((app) => {
  app.modules([myModule]);
  app.printLogger(Level.DEBUG); // Creates PrintLogger internally
});

No-Op Logger

Silent logger implementation that produces no output.

/**
 * Empty logger implementation that produces no output
 * Useful for production environments or testing
 */
class EmptyLogger extends Logger {
  /**
   * No-op display method - produces no output
   * @param level - Log level (ignored)
   * @param message - Message (ignored)
   */
  display(level: Level, message: string): void;
}

Usage Examples:

import { EmptyLogger, koinApplication } from "koin-core";

// Disable all logging
const silentApp = koinApplication((app) => {
  app.modules([productionModule]);
  app.logger(new EmptyLogger());
});

// Or use NONE level with PrintLogger
const silentApp2 = koinApplication((app) => {
  app.modules([productionModule]);
  app.printLogger(Level.NONE);
});

Application Logger Configuration

Configure logging during application setup with different strategies.

class KoinApplication {
  /**
   * Set custom logger implementation
   * @param logger - Custom Logger instance
   * @returns KoinApplication for chaining
   */
  logger(logger: Logger): KoinApplication;

  /**
   * Use default console logger with specified level
   * @param level - Log level (default: INFO)
   * @returns KoinApplication for chaining
   */
  printLogger(level?: Level): KoinApplication;
}

Usage Examples:

import { startKoin, module, Level, PrintLogger } from "koin-core";

// Development configuration with verbose logging
startKoin((app) => {
  app.modules([devModule]);
  app.printLogger(Level.DEBUG);
});

// Production configuration with custom logger
class ProductionLogger extends Logger {
  constructor() {
    super();
    this.logQueue = [];
  }
  
  display(level, message) {
    // Buffer logs and send in batches
    this.logQueue.push({ level, message, timestamp: Date.now() });
    
    if (this.logQueue.length >= 10) {
      this.flushLogs();
    }
  }
  
  flushLogs() {
    // Send logs to monitoring service
    this.sendToMonitoring(this.logQueue);
    this.logQueue = [];
  }
}

startKoin((app) => {
  app.modules([prodModule]);
  app.logger(new ProductionLogger());
});

// Testing configuration with no logging
startKoin((app) => {
  app.modules([testModule]);
  app.printLogger(Level.NONE);
});

Logging Context and Message Formatting

Enhanced logging with context information and structured messages.

/**
 * Enhanced logger with context support
 */
class ContextualLogger extends Logger {
  constructor(baseLogger, context) {
    super();
    this.baseLogger = baseLogger;
    this.context = context;
  }
  
  display(level, message) {
    const contextualMessage = `[${this.context}] ${message}`;
    this.baseLogger.display(level, contextualMessage);
  }
}

/**
 * Structured logger for JSON-formatted output
 */
class StructuredLogger extends Logger {
  constructor(outputFunction) {
    super();
    this.output = outputFunction || console.log;
  }
  
  display(level, message) {
    const logEntry = {
      timestamp: new Date().toISOString(),
      level: level,
      message: message,
      source: "koin-core"
    };
    
    this.output(JSON.stringify(logEntry));
  }
}

Usage Examples:

import { ContextualLogger, StructuredLogger, PrintLogger } from "koin-core";

// Contextual logging for different components
const dbLogger = new ContextualLogger(
  new PrintLogger(Level.DEBUG), 
  "DATABASE"
);

const apiLogger = new ContextualLogger(
  new PrintLogger(Level.INFO),
  "API"
);

// Structured logging for log aggregation
const structuredLogger = new StructuredLogger((jsonLog) => {
  // Send to log aggregation service
  console.log(jsonLog);
  // Example output: {"timestamp":"2024-01-15T10:30:00.000Z","level":"INFO","message":"Loading module","source":"koin-core"}
});

// Use contextual loggers in application
startKoin((app) => {
  app.modules([databaseModule]);
  app.logger(dbLogger);
});

Runtime Logger Control

Change logging configuration at runtime for dynamic control.

class Koin {
  /**
   * Update logger at runtime
   * @param logger - New logger instance
   */
  setLogger(logger: Logger): void;

  /**
   * Get current logger instance
   * @returns Current Logger
   */
  getLogger(): Logger;
}

Usage Examples:

import { GlobalContext, PrintLogger, EmptyLogger, Level } from "koin-core";

class LoggingManager {
  constructor() {
    this.debugMode = false;
  }
  
  enableDebugLogging() {
    if (!this.debugMode) {
      const koin = GlobalContext.get();
      koin.setLogger(new PrintLogger(Level.DEBUG));
      this.debugMode = true;
      console.log("Debug logging enabled");
    }
  }
  
  disableLogging() {
    const koin = GlobalContext.get();
    koin.setLogger(new EmptyLogger());
    this.debugMode = false;
    console.log("Logging disabled");
  }
  
  setLogLevel(level) {
    const koin = GlobalContext.get();
    koin.setLogger(new PrintLogger(level));
    console.log(`Log level set to: ${level}`);
  }
  
  getCurrentLogger() {
    const koin = GlobalContext.get();
    return koin.getLogger();
  }
}

// Usage
const loggingManager = new LoggingManager();

// Enable debug logging temporarily
loggingManager.enableDebugLogging();

// Process some operations...

// Disable logging for performance
loggingManager.disableLogging();

// Set specific log level
loggingManager.setLogLevel(Level.WARNING);

Logging Best Practices

Utilities and patterns for effective logging in Koin applications.

/**
 * Logging utilities for common patterns
 */
class LoggingUtils {
  /**
   * Create filtered logger that only logs specific patterns
   * @param baseLogger - Base logger to filter
   * @param filterFunction - Function to determine if message should be logged
   * @returns Filtered logger
   */
  static createFilteredLogger(baseLogger, filterFunction) {
    return new (class extends Logger {
      display(level, message) {
        if (filterFunction(level, message)) {
          baseLogger.display(level, message);
        }
      }
    })();
  }
  
  /**
   * Create rate-limited logger to prevent spam
   * @param baseLogger - Base logger to rate limit
   * @param maxMessagesPerSecond - Maximum messages per second
   * @returns Rate-limited logger
   */
  static createRateLimitedLogger(baseLogger, maxMessagesPerSecond = 10) {
    const messageQueue = [];
    const windowMs = 1000;
    
    return new (class extends Logger {
      display(level, message) {
        const now = Date.now();
        
        // Remove old messages outside window
        while (messageQueue.length > 0 && messageQueue[0] < now - windowMs) {
          messageQueue.shift();
        }
        
        // Check rate limit
        if (messageQueue.length < maxMessagesPerSecond) {
          messageQueue.push(now);
          baseLogger.display(level, message);
        }
      }
    })();
  }
}

Usage Examples:

import { LoggingUtils, PrintLogger, Level } from "koin-core";

// Filter out debug messages in production
const productionLogger = LoggingUtils.createFilteredLogger(
  new PrintLogger(Level.DEBUG),
  (level, message) => level !== Level.DEBUG || !message.includes("debug")
);

// Rate-limited logger to prevent log spam
const rateLimitedLogger = LoggingUtils.createRateLimitedLogger(
  new PrintLogger(Level.INFO),
  5 // Max 5 messages per second
);

// Use filtered logger
startKoin((app) => {
  app.modules([appModule]);
  app.logger(productionLogger);
});

Types

/** Abstract logger class */
abstract class Logger {
  abstract display(level: Level, message: string): void;
  debug(message: string): void;
  info(message: string): void;
  warn(message: string): void;
  error(message: string): void;
  isAt(level: Level): boolean;
}

/** Log levels enumeration */
enum Level {
  DEBUG = "DEBUG",
  INFO = "INFO", 
  WARNING = "WARNING",
  ERROR = "ERROR",
  NONE = "NONE"
}

/** Console-based logger implementation */
class PrintLogger extends Logger {
  constructor(level?: Level);
  display(level: Level, message: string): void;
}

/** No-op logger implementation */
class EmptyLogger extends Logger {
  display(level: Level, message: string): void;
}

/** Message type for logging */
type MESSAGE = string;

Install with Tessl CLI

npx tessl i tessl/maven-io-insert-koin--koin-core-js

docs

application-startup.md

context-management.md

dependency-injection.md

error-handling.md

index.md

logging-system.md

module-system.md

qualifiers-parameters.md

scoping-lifecycle.md

tile.json