Logger SDK Features
Feature overview
ByteHide Logger provides enterprise-grade logging capabilities with advanced features for security, performance, and observability.
Core Logging Features
Multi-Level Logging
Support for standard logging levels with intelligent filtering:
using Bytehide.Logger.Core;
// Different log levels
Log.Debug("Detailed diagnostic information");
Log.Info("General application flow");
Log.Warn("Potential issues or important notices");
Log.Error("Error conditions that need attention");
// With exceptions
try
{
// Some operation
}
catch (Exception ex)
{
Log.Error("Operation failed", ex);
}
Structured Logging
Log structured data for better analysis and querying:
// Log with structured data
Log.Info("User login", new {
UserId = "12345",
Username = "john.doe",
LoginTime = DateTime.UtcNow,
IpAddress = "192.168.1.100",
UserAgent = "Mozilla/5.0..."
});
// Log with custom properties
Log.WithContext("OrderId", "ORD-001")
.WithContext("CustomerId", "CUST-456")
.Info("Order processed successfully");
Security Features
Automatic Data Masking
Protect sensitive information automatically:
Log.Initialize(new LogSettings
{
MaskSensitiveData = new[] { "password", "token", "secret", "key" }
});
// Sensitive data is automatically masked
Log.Info("User credentials", new {
Username = "john.doe",
Password = "secret123", // Becomes "***"
ApiToken = "abc123xyz" // Becomes "***"
});
Custom Masking Rules
Define custom patterns for data masking:
Log.Initialize(new LogSettings
{
MaskSensitiveData = new[]
{
"password", "token", "secret", "key",
"credential", "connectionstring", "api_key",
"bearer_token", "auth_header", "private_key"
}
});
Performance Features
Duplicate Suppression
Prevent log flooding with intelligent duplicate detection:
Log.Initialize(new LogSettings
{
DuplicateSuppressionWindow = TimeSpan.FromSeconds(5)
});
// Only the first occurrence will be logged within 5 seconds
for (int i = 0; i < 100; i++)
{
Log.Warn("Database connection timeout"); // Logged once
}
Asynchronous Logging
Non-blocking logging for high-performance applications:
// Asynchronous logging methods
await Log.InfoAsync("Async operation completed");
await Log.ErrorAsync("Async operation failed", exception);
// Fire-and-forget logging (non-blocking)
Log.Info("High-frequency event"); // Returns immediately
Memory-Efficient Logging
Optimized for minimal memory allocation:
// Efficient string interpolation
Log.Info($"Processing order {orderId} for customer {customerId}");
// Lazy evaluation for expensive operations
Log.Debug(() => $"Complex calculation result: {ExpensiveCalculation()}");
Advanced Logging Features
Correlation IDs
Track requests across distributed systems:
// Set correlation ID for the current context
Log.SetCorrelationId("REQ-12345");
// All subsequent logs will include this correlation ID
Log.Info("Processing started");
Log.Info("Validation completed");
Log.Info("Processing finished");
// Clear correlation ID
Log.ClearCorrelationId();
User Identification
Associate logs with specific users:
using Bytehide.Logger.Common.Models.Users;
// Identify user for all subsequent logs
Log.Identify(new AuthUser
{
Id = "user-123",
Email = "john.doe@company.com",
Name = "John Doe"
});
Log.Info("User action performed"); // Includes user context
// Clear user identification
Log.ClearIdentity();
Global Properties
Add properties that appear in all log entries:
// Set global properties
Log.AddGlobalProperty("ApplicationVersion", "2.1.0");
Log.AddGlobalProperty("Environment", "Production");
Log.AddGlobalProperty("MachineName", Environment.MachineName);
// All logs will now include these properties
Log.Info("Application started");
// Remove global properties
Log.RemoveGlobalProperty("ApplicationVersion");
Tags and Context
Organize and filter logs with tags:
// Add tags to logs
Log.WithTags("payment", "critical")
.Info("Payment processing initiated");
// Add context data
Log.WithContext("TransactionId", "TXN-789")
.WithContext("Amount", 99.99m)
.WithTags("payment", "success")
.Info("Payment completed");
// Chain multiple context items
Log.WithContext("UserId", userId)
.WithContext("SessionId", sessionId)
.WithContext("Feature", "checkout")
.Info("Checkout process started");
File Management Features
Automatic File Rotation
Intelligent log file management:
Log.Initialize(new LogSettings
{
Persist = true,
FilePath = "logs/app.log",
// Time-based rotation
RollingInterval = RollingInterval.Day,
// Size-based rotation
RollOnFileSizeLimit = true,
FileSizeLimitBytes = 10 * 1024 * 1024, // 10 MB
// Maximum total log size
MaxFileSize = 100 * 1024 * 1024 // 100 MB
});
Log Compression
Automatic compression of rotated log files:
Log.Initialize(new LogSettings
{
Persist = true,
FilePath = "logs/app.log",
RollingInterval = RollingInterval.Day,
CompressRotatedFiles = true // Compress old log files
});
Observability Features
Performance Metrics
Built-in performance tracking:
// Measure operation duration
using (Log.BeginScope("DatabaseOperation"))
{
// Database operation
var result = await database.QueryAsync();
Log.Info("Query executed", new { RowCount = result.Count() });
} // Automatically logs operation duration
Health Monitoring
Monitor logger health and performance:
// Get logger statistics
var stats = Log.GetStatistics();
Console.WriteLine($"Total logs: {stats.TotalLogs}");
Console.WriteLine($"Errors: {stats.ErrorCount}");
Console.WriteLine($"Average write time: {stats.AverageWriteTime}ms");
Custom Metrics
Track custom application metrics:
// Increment counters
Log.IncrementCounter("user.login.count");
Log.IncrementCounter("order.processed.count");
// Record values
Log.RecordValue("response.time.ms", responseTime);
Log.RecordValue("memory.usage.mb", memoryUsage);
Integration Features
Exception Enrichment
Automatic exception context enrichment:
try
{
// Some operation
}
catch (Exception ex)
{
// Automatically includes stack trace, inner exceptions, and context
Log.Error("Operation failed", ex);
}
Caller Information
Automatic source code location tracking:
Log.Initialize(new LogSettings
{
IncludeCallerInfo = true
});
// Automatically includes method name, file, and line number
Log.Info("Debug checkpoint"); // [Info] [MyMethod:Program.cs:42] Debug checkpoint
Environment Detection
Automatic environment context:
// Automatically detects and includes:
// - Machine name
// - Process ID
// - Thread ID
// - Application domain
// - Environment variables (configurable)
Log.Info("Application context captured");
Configuration Reset and Management
Runtime Configuration Changes
Modify logger behavior at runtime:
// Change log level dynamically
Log.SetMinimumLevel(LogLevel.Debug);
// Enable/disable features
Log.EnableConsole();
Log.DisableConsole();
// Update file path
Log.SetFilePath("logs/new-location.log");
Configuration Reset
Reset logger to default state:
// Reset all configuration to defaults
Log.ResetConfiguration();
// Clear all context and global properties
Log.ClearAllContext();
// Disable logging temporarily
Log.Disable();
// Re-enable logging
Log.Enable();