Skip to content

Logger

The Logger submodule provides a robust, structured utility for logging messages both synchronously and asynchronously within Apex transactions. It supports log-level thresholding, exception formatting, and asynchronous log publishing via Platform Events.

Documentation

💾 Source Code

Implementation

  • Provides support for logging to different targets:
    • SYSTEM_DEBUG: Publishes immediately to Salesforce debug logs using System.debug()
    • PLATFORM_EVENT: Queues logs to be published asynchronously as Platform Events (Log_Event__e)
    • ALL: Performs both actions
  • The logger checks severity thresholds prior to queuing logs. Mapped to Salesforce's native LoggingLevel enum, only messages meeting or exceeding the current logger's threshold are published
  • Instantiated either via default constructor (defaults to WARN level and ALL target) or declarative configurations via the Logger_Configuration__mdt custom metadata type
  • Exceptions are parsed and formatted into structured JSON strings containing:
    • exceptionType
    • message
    • lineNumber
    • stackTrace

Demos

apex
// Instantiate the logger (by default uses WARN / ALL)
Logger logger = new Logger();

// Logging statements
logger.info('Starting transaction processing'); // Skipped if default is WARN
logger.warn('Resource usage is high');          // Logged to System.debug / queued
logger.error('Critical database mismatch');     // Logged to System.debug / queued

try {
    Integer result = 10 / 0;
} catch (Exception ex) {
    // Automatically formats exception into structured JSON with stack trace
    logger.error(ex);
}

// Publish queued Platform Events
logger.flush();
apex
// Load the default metadata configuration record
Logger_Configuration__mdt config = Logger.getDefaultConfiguration();
Logger configLogger = new Logger(config);

configLogger.debug('Running with metadata-driven logging settings');
configLogger.flush();

Benefits

  • Writing to Platform Events allows for asynchronous logging without blocking transactions
  • Modify debug logs at runtime by updating the Logger_Configuration__mdt records without redeploying code
  • Captures Quiddity and Request IDs automatically making troubleshooting distributed transactions, asynchronous calls, and integrations significantly faster

SlightWork is part of the Wynforce ecosystem