LoggingHelper Documentation

A comprehensive guide to the LoggingHelper Documentation

LoggingHelper Documentation

Overview

The LoggingHelper class provides comprehensive logging functionality with support for multiple logging sinks, structured logging, performance metrics, and audit events. It uses Serilog as the underlying logging framework.

Features

Usage

Initialization

var options = new LoggingOptions
{
    MinimumLevel = LogEventLevel.Information,
    EnableConsole = true,
    ConsoleTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
    EnableFile = true,
    FilePath = "logs/app.log",
    RetainedFileCount = 31,
    EnableElasticsearch = true,
    ElasticsearchUrl = "http://localhost:9200",
    ElasticsearchIndex = "logs-{0:yyyy.MM}"
};

LogHelper.Initialize(options);

Basic Logging

LogHelper.Verbose("Detailed debugging information");
LogHelper.Debug("Debugging information");
LogHelper.Information("General information");
LogHelper.Warning("Warning message");
LogHelper.Error("Error message");
LogHelper.Fatal("Fatal error message");

Exception Logging

try
{
    // Some code that might throw
}
catch (Exception ex)
{
    LogHelper.Exception(ex, "An error occurred while processing {Item}", itemName);
}

Scoped Logging

using (LogHelper.BeginScope(new Dictionary
{
    ["UserId"] = userId,
    ["RequestId"] = requestId
}))
{
    LogHelper.Information("Processing request");
    // All logs within this scope will include UserId and RequestId
}

Performance Metrics

LogHelper.LogMetric("ProcessingTime", 150.5, "ms", new Dictionary
{
    ["Operation"] = "DataSync",
    ["BatchSize"] = 1000
});

Audit Events

LogHelper.LogAudit(
    action: "UserCreated",
    resource: "Users",
    user: "admin@example.com",
    details: new { UserId = 123, Role = "Admin" }
);

Security Events

LogHelper.LogSecurity(
    eventType: "UnauthorizedAccess",
    severity: SecuritySeverity.High,
    message: "Invalid login attempt",
    details: new { Username = "user", IpAddress = "192.168.1.1" }
);

Performance Measurement

var result = await LogHelper.MeasureExecutionTime(
    async () =>
    {
        // Long running operation
        return await ProcessData();
    },
    "DataProcessing"
);

Options Class

LoggingOptions

Security Severity Levels

public enum SecuritySeverity
{
    Low,
    Medium,
    High,
    Critical
}

Best Practices

  1. Log Levels

    • Use Verbose for detailed debugging
    • Use Debug for general debugging
    • Use Information for general information
    • Use Warning for potential issues
    • Use Error for actual errors
    • Use Fatal for catastrophic failures
  2. Structured Logging

    • Use structured log messages with named parameters
    • Include relevant context in log scopes
    • Use semantic logging for metrics and events
  3. Performance

    • Use appropriate log levels to avoid unnecessary logging
    • Consider using async logging for high-throughput scenarios
    • Monitor log file sizes and implement rotation
  4. Security

    • Never log sensitive information
    • Use appropriate security severity levels
    • Include relevant security context in audit logs

Error Handling

The helper automatically handles logging errors internally. If initialization fails, it will use default settings to ensure logging continues to function.

Legal Disclaimer

This documentation and associated helper scripts are provided "as is" without warranty of any kind, either express or implied.

  1. The code examples and helper functions are for illustrative purposes only.
  2. Users should thoroughly test any implementation in their specific environment.
  3. The authors are not responsible for any issues or damages arising from the use of these scripts.
  4. Always follow security best practices and your organization's coding guidelines.