Table of Contents


Working with Event Logs

Overview

The Magentrix platform provides a robust event logging system that allows developers to write diagnostic information, warnings, and errors to a centralized log. The platform's logging infrastructure writes to the database and provides UI-based log viewing and filtering capabilities.

Event logs are essential for:

  • Debugging custom code and troubleshooting issues
  • Monitoring application behavior in production
  • Tracking warnings and errors for proactive maintenance
  • Auditing system operations
💡 Note: Event logs can be viewed by administrators through the Magentrix IDE under Tools > Event Logs.

Log Levels

Magentrix supports multiple log levels that control the verbosity of logging. The log level is configured in Company Preferences > System Settings > Under the Hood > Log Level.

Log LevelWhat Gets LoggedUse Case
OffNothingProduction environments where logging is not needed
WarningWarnings onlyMinimal logging for non-critical issues
ErrorWarnings + ErrorsStandard production setting
DebugWarnings + Errors + Debug messagesDevelopment and troubleshooting
Information   Warnings + Errors + Debug + InformationSystem-level logging (not available to developers)
VerboseAll log types including verbose system details  Deep diagnostics (not available to developers)

 

⚠️ Warning: Setting the log level to Information or Verbose can significantly impact performance and generate excessive log entries. These levels are reserved for system-level diagnostics and should not be used for extended periods.

Logging Methods

Magentrix provides logging capability though use of SystemInfo class. The SystemInfo class provides convenient shortcuts and is automatically available in ActiveClasses and Controllers.


SystemInfo Class Methods

The SystemInfo static class provides the simplest way to write log entries.

Debug

Writes a debug-level message to the event log.

Signature:

public static void Debug(string message, params object[] args)

Parameters:

  • message (string): The message to log. Supports string formatting with placeholders.
  • args (params object[]): Optional arguments for string formatting.

Returns:void

Example:

// Simple message
SystemInfo.Debug("Processing started");

// With formatting (string interpolation)
int recordId = 12345;
SystemInfo.Debug($"Processing record {recordId}");

// With formatting (placeholder style)
SystemInfo.Debug("Processing record {0} at {1}", recordId, DateTime.Now);

Warning

Writes a warning-level message to the event log.

Signature:

public static void Warning(string message, params object[] args)

Parameters:

  • message (string): The warning message to log. Supports string formatting with placeholders.
  • args (params object[]): Optional arguments for string formatting.

Returns:void

Example:

// Simple warning
SystemInfo.Warning("Cache expiration time is approaching");

// With formatting
string userName = "john.doe";
SystemInfo.Warning($"User {userName} attempted unauthorized access");

// With multiple parameters
SystemInfo.Warning("Failed to load {0} after {1} attempts", resourceName, retryCount);

Error (Message)

Writes an error-level message to the event log.

Signature:

public static void Error(string message, params object[] args)

Parameters:

  • message (string): The error message to log. Supports string formatting with placeholders.
  • args (params object[]): Optional arguments for string formatting.

Returns:void

Example:

// Simple error message
SystemInfo.Error("Database connection failed");

// With formatting
string connectionString = "Server=localhost;Database=MyDb";
SystemInfo.Error($"Failed to connect using: {connectionString}");

// With multiple parameters
SystemInfo.Error("Error processing entity {0}: {1}", entityId, errorDescription);

Error (Exception)

Writes an exception to the event log, including the exception message, stack trace, and inner exceptions.

Signature:

public static void Error(Exception ex)

Parameters:

  • ex (Exception): The exception object to log.

Returns:void

Example:

try
{
    // Your code here
}
catch (Exception ex)
{
    SystemInfo.Error(ex);
}
💡 Note: This method automatically captures the full exception details including stack trace and inner exceptions, making it ideal for comprehensive error logging.

Viewing Event Logs

To view event logs:

  1. Log in to the Magentrix IDE as an administrator
  2. Navigate to Tools > Event Logs
  3. Use the filtering options to search by:
    • Log level (Off, Warning, Error, Debug, Information, Verbose)
    • Date range
    • Message content

💡 Note: Only administrators have access to view event logs.


Best Practices

Performance Considerations

Since event logs are written to the database, excessive logging can impact system performance:

  • Avoid logging in tight loops or high-frequency operations
  • Use appropriate log levels (don't log everything at Debug level in production)
  • Be mindful of log message size (avoid logging large data structures)
  • Set the log level to Error in production environments unless actively troubleshooting

Example of what to avoid:

// ❌ Bad: Logging inside a loop
foreach (var item in largeCollection)
{
    SystemInfo.Debug($"Processing item {item.Id}"); // This will create thousands of log entries
}

Better approach:

// ✅ Good: Log summary information
SystemInfo.Debug($"Starting batch processing of {largeCollection.Count} items");
// ... process items ...
SystemInfo.Debug($"Completed batch processing. Success: {successCount}, Failed: {failCount}");

Log Retention

Event logs are automatically retained for 60 days and then purged from the system. Plan your logging strategy accordingly:

  • Critical events should be logged at Error or Warning level
  • Avoid relying on Debug logs for long-term historical analysis
  • Export important logs if you need to retain them beyond 60 days

Security and Sensitive Data

Never log sensitive information such as:

  • Passwords or API keys
  • Credit card numbers
  • Personal Identifiable Information (PII) unless absolutely necessary
  • Authentication tokens or session IDs

Example:

// ❌ Bad: Logging sensitive data
SystemInfo.Debug($"User login: {username}, Password: {password}");

// ✅ Good: Log without sensitive data
SystemInfo.Debug($"User login attempt: {username}");

When to Use Each Log Level

LevelWhen to UseExample
DebugDevelopment and troubleshooting"Entering CalculateDiscount method", "Query returned 15 results"
Warning  Non-critical issues that don't stop execution"API rate limit approaching", "Cache miss for key {key}"
ErrorFailures that prevent normal operation"Failed to save record", "External API returned 500 error"

Usage Examples

Example 1: Logging in an ActiveClass

public class OrderProcessor : ActiveClassBase
{
    public override void Execute()
    {
        try
        {
            SystemInfo.Debug("OrderProcessor.Execute started");
            
            var orderId = GetParameter("OrderId");
            var order = EntityManager.GetById("Order", orderId);
            
            if (order == null)
            {
                SystemInfo.Warning($"Order {orderId} not found");
                return;
            }
            
            // Process the order
            ProcessOrder(order);
            
            SystemInfo.Debug($"Order {orderId} processed successfully");
        }
        catch (Exception ex)
        {
            SystemInfo.Error(ex);
            throw;
        }
    }
    
    private void ProcessOrder(Entity order)
    {
        // Processing logic here
    }
}

Example 2: Logging in a Controller

public class CustomOrderController : BaseController
{
    [HttpPost]
    public ActionResult SubmitOrder(string orderId)
    {
        try
        {
            SystemInfo.Debug($"SubmitOrder called for order {orderId}");
            
            // order logic goes here
            
            if (!ValidateOrder(order))
            {
                SystemInfo.Warning($"Order validation failed for {orderId}");
                return Json(new { success = false, message = "Invalid order" });
            }
            
            // Submit order logic
            SubmitToPaymentGateway(order);
            
            SystemInfo.Debug($"Order {orderId} submitted successfully");
            return Json(new { success = true });
        }
        catch (Exception ex)
        {
            SystemInfo.Error(ex);
            return Json(new { success = false, message = "An error occurred" });
        }
    }
}

Example 3: Logging with Formatted Messages

// Using string interpolation
string userId = "12345";
string action = "Delete";
SystemInfo.Debug($"User {userId} performed action: {action}");

// Using placeholder formatting
SystemInfo.Debug("User {0} performed action: {1}", userId, action);

// Multiple parameters
int recordCount = 150;
TimeSpan duration = TimeSpan.FromSeconds(3.5);
SystemInfo.Debug("Processed {0} records in {1} seconds", recordCount, duration.TotalSeconds);

Example 4: Using EventLogProvider Directly

public class DataSyncService
{
    public void SyncData()
    {
        SystemInfo.Debug("Starting data synchronization");
        
        try
        {
            var records = FetchExternalData();
            SystemInfo.Debug($"Retrieved {records.Count} records from external system");
            
            foreach (var record in records)
            {
                ImportRecord(record);
            }
            
            SystemInfo.Debug("Data synchronization completed successfully");
        }
        catch (Exception ex)
        {
            SystemInfo.Error(ex);
            SystemInfo.Error("Data synchronization failed");
        }
    }
}

Troubleshooting

Logs Not Appearing

If your log entries are not appearing in the Event Logs viewer:

  1. Check the Log Level setting in Company Preferences > System Settings > Under the Hood

    • Ensure the log level is set appropriately (e.g., Debug for development)
    • Remember that logs will only appear if they match or exceed the configured level
  2. Verify you're logged in as an administrator

    • Only administrators can view event logs
  3. Check the date filter in the Event Logs viewer

    • Ensure you're viewing the correct date range
  4. Confirm your code is executing

    • Add a test log entry at a higher level (Error or Warning) to verify execution

Performance Issues

If you're experiencing performance degradation:

  1. Lower the log level to Error or Warning in production
  2. Review your code for excessive logging (especially in loops)
  3. Check log retention - the 60-day retention period is automatic, but a large volume of logs can still impact performance temporarily

Summary

The Magentrix event logging system provides:

  • Two equivalent interfaces: SystemInfo (shortcut) and EventLogProvider.Current (direct)
  • Multiple log levels: Debug, Warning, Error
  • String formatting support: Use $"{variable}" or "{0}" placeholder syntax
  • Exception logging: Automatic capture of stack traces and inner exceptions
  • UI-based log viewing: Tools > Event Logs in the Magentrix IDE
  • 60-day retention: Automatic cleanup of old log entries

Use event logs strategically to maintain system performance while gaining valuable diagnostic insights into your custom code behavior.