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
- Multiple logging sinks (Console, File, Elasticsearch)
- Structured logging with context
- Performance metrics logging
- Audit and security event logging
- Log scoping and correlation
- Configurable log levels and templates
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
MinimumLevel
: Minimum log level to captureEnableConsole
: Enable console loggingConsoleTemplate
: Console output templateConsoleMinLevel
: Minimum level for console outputEnableFile
: Enable file loggingFilePath
: Log file pathFileTemplate
: File output templateRetainedFileCount
: Number of log files to retainEnableElasticsearch
: Enable Elasticsearch loggingElasticsearchUrl
: Elasticsearch server URLElasticsearchIndex
: Index name format
Security Severity Levels
public enum SecuritySeverity
{
Low,
Medium,
High,
Critical
}
Best Practices
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
Structured Logging
- Use structured log messages with named parameters
- Include relevant context in log scopes
- Use semantic logging for metrics and events
Performance
- Use appropriate log levels to avoid unnecessary logging
- Consider using async logging for high-throughput scenarios
- Monitor log file sizes and implement rotation
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.
- The code examples and helper functions are for illustrative purposes only.
- Users should thoroughly test any implementation in their specific environment.
- The authors are not responsible for any issues or damages arising from the use of these scripts.
- Always follow security best practices and your organization's coding guidelines.
