{"id":26121468,"url":"https://github.com/rpdevjesco/annotationlogframework","last_synced_at":"2025-09-20T08:38:52.167Z","repository":{"id":281417099,"uuid":"945215592","full_name":"RPDevJesco/AnnotationLogFramework","owner":"RPDevJesco","description":"A high-performance, attributes-based .NET logging framework that enables aspect-oriented logging with minimal code clutter","archived":false,"fork":false,"pushed_at":"2025-03-08T23:27:09.000Z","size":25,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-09T00:19:42.265Z","etag":null,"topics":["aspect-oriented-programming","csharp-library","dotnet-core","logging-library"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/RPDevJesco.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-03-08T23:13:49.000Z","updated_at":"2025-03-08T23:25:17.000Z","dependencies_parsed_at":"2025-03-09T00:30:21.666Z","dependency_job_id":null,"html_url":"https://github.com/RPDevJesco/AnnotationLogFramework","commit_stats":null,"previous_names":["rpdevjesco/annotationlogframework"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RPDevJesco%2FAnnotationLogFramework","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RPDevJesco%2FAnnotationLogFramework/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RPDevJesco%2FAnnotationLogFramework/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RPDevJesco%2FAnnotationLogFramework/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/RPDevJesco","download_url":"https://codeload.github.com/RPDevJesco/AnnotationLogFramework/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242864827,"owners_count":20197787,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aspect-oriented-programming","csharp-library","dotnet-core","logging-library"],"created_at":"2025-03-10T14:22:27.806Z","updated_at":"2025-09-20T08:38:52.160Z","avatar_url":"https://github.com/RPDevJesco.png","language":"C#","readme":"# AnnotationLogger\n\nA high-performance, attributes-based .NET logging framework that brings clean code and aspect-oriented programming principles to your application logging.\n\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n## Table of Contents\n\n- [Overview](#overview)\n- [Key Features](#key-features)\n- [Why AnnotationLogger?](#why-annotationlogger)\n  - [Comparison with Popular Logging Libraries](#comparison-with-popular-logging-libraries)\n  - [Benefits Over Traditional Loggers](#benefits-over-traditional-loggers)\n- [Getting Started](#getting-started)\n  - [Installation](#installation)\n  - [Basic Setup](#basic-setup)\n  - [First Log](#first-log)\n- [Core Components](#core-components)\n  - [LogManager](#logmanager)\n  - [LoggedMethodCaller](#loggedmethodcaller)\n  - [CorrelationManager](#correlationmanager)\n- [Logging Attributes](#logging-attributes)\n  - [Basic Usage](#basic-attributes-usage)\n  - [Customizing Attributes](#customizing-attributes)\n- [Advanced Features](#advanced-features)\n  - [Data Change Tracking](#data-change-tracking)\n  - [Performance Monitoring](#performance-monitoring)\n  - [Progress Logging](#progress-logging)\n  - [Log Throttling](#log-throttling)\n  - [Sensitive Data Protection](#sensitive-data-protection)\n  - [Log Routing](#log-routing)\n  - [Database Logging](#database-logging)\n- [Configuration Options](#configuration-options)\n- [Implementation Details](#implementation-details)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Overview\n\nAnnotationLogger is a comprehensive logging framework for .NET applications that provides attribute-based method logging, performance tracking, data change monitoring, and more. The framework is designed to be both simple to use and highly configurable, supporting a variety of logging destinations and formats.\n\n## Key Features\n\n- **Attributes-Based Logging**: Simply annotate methods with `[LogDebug]`, `[LogInfo]`, `[LogWarning]`, etc.\n- **Expression-Based Method Interception**: Uses expression trees for powerful method introspection\n- **Automatic Parameter Logging**: Captures method parameters automatically\n- **Return Value Logging**: Records method outputs for complete invocation tracking\n- **Exception Tracking**: Automatically captures and logs exceptions with stack traces\n- **Execution Time Measurement**: Built-in performance tracking via Stopwatch integration\n- **Async Support**: Full support for async/await methods via Task-based interfaces\n- **Extensible Output**: Console, file, database, and composite loggers with structured output options\n- **Environment-Aware**: Configure different logging behaviors for development vs. production\n- **Distributed Tracing**: Built-in correlation ID management for trace context propagation\n- **Thread-Safe**: Implements proper synchronization for multi-threaded environments\n- **Data Change Tracking**: Track changes to objects across method calls\n- **Progress Monitoring**: Log progress for long-running operations\n- **Log Throttling**: Control log volume in high-frequency methods\n- **Advanced Routing**: Direct logs to different destinations based on content\n\n## Why AnnotationLogger?\n\n### Comparison with Popular Logging Libraries\n\n| Feature | AnnotationLogger | Serilog | NLog | log4net |\n|---------|-----------------|---------|------|---------|\n| Aspect-Oriented Logging | ✅ | ❌ | ❌ | ❌ |\n| Clean Business Logic | ✅ | ❌ | ❌ | ❌ |\n| Automatic Parameter Capture | ✅ | ❌ | ❌ | ❌ |\n| Fluent Configuration | ✅ | ✅ | ✅ | ❌ |\n| Structured Logging | ✅ | ✅ | ✅ | ❌ |\n| Performance Tracking | ✅ | ❌ | ❌ | ❌ |\n| Data Change Tracking | ✅ | ❌ | ❌ | ❌ |\n| Progress Logging | ✅ | ❌ | ❌ | ❌ |\n| Performance | High | High | Medium | Medium |\n| Learning Curve | Medium | Low | Medium | High |\n\n### Benefits Over Traditional Loggers\n\n**1. Separation of Concerns**\n\nUnlike traditional logging frameworks that require you to inject logging code throughout your business logic, AnnotationLogger cleanly separates your application code from your logging concerns. This leads to more maintainable, readable code.\n\n**2. Reduced Boilerplate**\n\nTraditional logging approaches may require 5-10 lines of code per method for proper entry/exit logging. With AnnotationLogger, it's just one line - the attribute declaration:\n\n```csharp\n[LogInfo]\npublic Customer GetCustomerById(int customerId)\n{\n    // Your business logic here, no logging code!\n    return _repository.FindById(customerId);\n}\n```\n\n**3. Consistent Logging Standard**\n\nAnnotationLogger ensures all methods are logged consistently following the same pattern and level of detail. This prevents developer-by-developer inconsistencies that plague many codebases.\n\n**4. Better for AOP**\n\nTrue aspect-oriented programming for logging, separating cross-cutting concerns from your business logic in a clean, maintainable way.\n\n**5. Automatic Parameter Handling**\n\nParameter values are automatically captured and formatted intelligently based on their type, with special handling for collections, dictionaries, and complex objects.\n\n## Getting Started\n\n### Installation\n\nAdd AnnotationLogger to your project using your preferred method:\n\n```bash\ndotnet add package AnnotationLogger\n```\n\n### Basic Setup\n\nSet up AnnotationLogger in your application startup code:\n\n```csharp\nusing AnnotationLogger;\n\n// Configure logger in Program.cs or Startup.cs\nLogManager.Configure(config =\u003e \n{\n    config.Logger = new ConsoleLogger();\n    config.Environment = EnvironmentType.Development;\n});\n\n// Optional: Configure data change tracking\nLogManager.ConfigureDataLogging(config =\u003e \n{\n    config.EnableDataChangeTracking = true;\n    config.MaxComparisonDepth = 3;\n});\n```\n\n### First Log\n\nCreate a class with logged methods and then call them using `LoggedMethodCaller`:\n\n```csharp\n// Define a class with logging attributes\npublic class UserService\n{\n    [LogInfo]\n    public User GetUser(int userId)\n    {\n        // Business logic here\n        return new User { Id = userId, Name = \"John\" };\n    }\n}\n\n// Use LoggedMethodCaller to invoke the method with logging\nvar userService = new UserService();\nUser user = LoggedMethodCaller.Call(() =\u003e userService.GetUser(123));\n```\n\n## Core Components\n\n### LogManager\n\nThe central static class that manages all logging configurations and operations.\n\n```csharp\n// Configure general logging\nLogManager.Configure(config =\u003e \n{\n    config.Logger = new ConsoleLogger();\n    config.Environment = EnvironmentType.Development;\n});\n\n// Direct logging methods\nLogManager.Info(\"Application started\");\nLogManager.Warning(\"Unusual condition detected\");\nLogManager.Error(\"Operation failed\", new Dictionary\u003cstring, object\u003e { \n    { \"ErrorCode\", 500 }, \n    { \"Details\", \"Connection timeout\" } \n});\n\n// Add context information\nLogManager.AddContext(\"TraceId\", Guid.NewGuid().ToString());\nLogManager.AddContext(\"SessionId\", sessionId);\n```\n\n### LoggedMethodCaller\n\nThe main API for automatic method interception and logging.\n\n```csharp\n// For methods that return a value\nint result = LoggedMethodCaller.Call(() =\u003e calculator.Add(5, 3));\n\n// For methods that don't return a value\nLoggedMethodCaller.Call(() =\u003e dataService.ProcessRecord(record));\n\n// For async methods\nUser user = await LoggedMethodCaller.CallAsync(() =\u003e userService.GetUserAsync(123));\nawait LoggedMethodCaller.CallAsync(() =\u003e notificationService.SendNotificationsAsync());\n```\n\n### CorrelationManager\n\nManages correlation IDs for tracking related log entries across multiple components.\n\n```csharp\n// Start a new logical operation\nCorrelationManager.StartNewCorrelation();\n\n// Get the current correlation ID\nstring correlationId = CorrelationManager.CurrentCorrelationId;\n\n// Pass to other systems\nhttpClient.DefaultRequestHeaders.Add(\"X-Correlation-ID\", correlationId);\n```\n\n## Logging Attributes\n\n### Basic Attributes Usage\n\n```csharp\n// Different logging levels\n[LogTrace]\npublic void HighDetailDiagnostics() { }\n\n[LogDebug]\npublic List\u003cstring\u003e GetDebugInfo() { }\n\n[LogInfo]\npublic User CreateUser(UserRequest request) { }\n\n[LogWarning]\npublic bool ValidateInput(string input) { }\n\n[LogError]\npublic void ProcessPayment(Payment payment) { }\n\n[LogCritical]\npublic void UpdateSystemConfig(SystemConfig config) { }\n\n// Logs in all environments, including production\n[LogProd]\npublic void BusinessCriticalOperation() { }\n```\n\n### Customizing Attributes\n\n```csharp\n// Control what gets logged\n[LogInfo(\n    IncludeParameters = true,       // Log method parameters\n    IncludeReturnValue = true,      // Log return value\n    IncludeExecutionTime = true     // Log execution time\n)]\npublic Report GenerateReport(ReportRequest request) { }\n\n// With progress logging for long operations\n[LogInfo]\n[WithProgressLogging(intervalMs: 1000)]  // Log progress every second\npublic async Task ImportLargeDatasetAsync() { }\n```\n\n## Advanced Features\n\n### Data Change Tracking\n\nTrack changes to objects across method calls:\n\n```csharp\n[TrackDataChanges(\n    IncludeOriginalState = true,     // Include original state in logs\n    IncludeUpdatedState = true,      // Include updated state in logs\n    OperationType = \"UserUpdate\"     // Custom operation name\n)]\npublic User UpdateUser([BeforeChange] User user, UserUpdateRequest request)\n{\n    // Update user properties\n    user.Name = request.Name;\n    user.Email = request.Email;\n    \n    return user;\n}\n```\n\n### Performance Monitoring\n\n```csharp\n// Performance tracking happens automatically for logged methods\n[LogInfo]\npublic void PerformanceIntensiveOperation() { }\n\n// Get performance statistics after running your application\nvar stats = LogManager.GetPerformanceTracker().GetStats();\nforeach (var stat in stats)\n{\n    Console.WriteLine($\"Method: {stat.Value.MethodName}\");\n    Console.WriteLine($\"  Calls: {stat.Value.CallCount}\");\n    Console.WriteLine($\"  Avg Time: {stat.Value.AverageTime:F2}ms\");\n}\n```\n\n### Progress Logging\n\n```csharp\n// Automatic progress logging for long operations\n[LogInfo]\n[WithProgressLogging(intervalMs: 1000)]\npublic async Task ProcessBatchesAsync(IEnumerable\u003cDataBatch\u003e batches)\n{\n    foreach (var batch in batches)\n    {\n        await Task.Delay(500); // Simulate work\n        // Process batch...\n    }\n}\n\n// Manual progress logging\nusing (var progressLogger = new ProgressLogger(\"Import Operation\", 2000))\n{\n    // Long-running operation...\n}\n```\n\n### Log Throttling\n\n```csharp\n// Prevent log flooding in high-frequency operations\n[LogDebug]\n[ThrottleLogging(MaxLogsPerSecond = 5)]\npublic double CalculateValue(double input)\n{\n    // High-frequency operation\n    return Math.Pow(input, 2);\n}\n```\n\n### Sensitive Data Protection\n\n```csharp\npublic class User\n{\n    public string Username { get; set; }\n    \n    [MaskInLogs(ShowFirstChars = true, FirstCharsCount = 1)]\n    public string Password { get; set; }  // \"p***\"\n    \n    [MaskInLogs(ShowFirstChars = true, FirstCharsCount = 3, \n                ShowLastChars = true, LastCharsCount = 4)]\n    public string Email { get; set; }  // \"joh***ple.com\"\n    \n    [RedactContents(ReplacementText = \"[CREDIT CARD REDACTED]\")]\n    public string CreditCardNumber { get; set; }\n    \n    [ExcludeFromLogs]\n    public string ApiKey { get; set; }  // Excluded completely\n}\n```\n\n### Log Routing\n\n```csharp\n// Create a router with custom routing rules\nvar router = new LogRouter(new ConsoleLogger())\n    // Send all errors to an error log file\n    .AddRoute(entry =\u003e entry.Level \u003e= LogLevel.Error, \n              new FileLogger(LogLevel.Error, \"errors.log\"))\n    \n    // Send debug logs to a debug file\n    .AddRoute(entry =\u003e entry.Level == LogLevel.Debug,\n              new FileLogger(LogLevel.Debug, \"debug.log\"))\n    \n    // Send security-related logs to a secure log\n    .AddRoute(entry =\u003e entry.Message.Contains(\"security\"),\n              new FileLogger(LogLevel.Info, \"security.log\"))\n    \n    // Send data changes to a database\n    .AddRoute(entry =\u003e entry.HasDataChanges,\n              new DatabaseLogger(LogLevel.Info, \"Data Source=audit.db\"));\n\nLogManager.Configure(config =\u003e \n{\n    config.Logger = router;\n});\n```\n\n### Database Logging\n\n```csharp\n// Configure logging to a SQLite database\nstring dbPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"logs/logs.db\");\nvar dbLogger = new DatabaseLogger(LogLevel.Info, $\"Data Source={dbPath}\");\n// Create the logs directory if it doesn't exist\nDirectory.CreateDirectory(logDirectory);\nLogManager.Configure(config =\u003e \n{\n    config.Logger = new CompositeLogger(new[] {\n        new ConsoleLogger(),\n        dbLogger\n    });\n});\n```\n\n## Configuration Options\n\nConfigure AnnotationLogger with various options:\n\n```csharp\nLogManager.Configure(config =\u003e \n{\n    // Logger and environment\n    config.Logger = new CompositeLogger(new[] {\n        new ConsoleLogger(),\n        new FileLogger(\"app.log\")\n    });\n    config.Environment = EnvironmentType.Development;\n    \n    // What to include in logs\n    config.EnableMethodEntryExit = true;\n    config.EnableParameterLogging = true;\n    config.EnableReturnValueLogging = true;\n    config.EnableExecutionTimeLogging = true;\n    \n    // Output format\n    config.UseStructuredOutput = false;  // Set to true for JSON\n    \n    // Advanced settings\n    config.MaxStringLength = 10000;      // Truncate long strings\n    config.MaxCollectionItems = 100;     // Limit collection items\n    config.IncludeStackTraces = true;\n    config.MaxObjectDepth = 3;           // Nested object depth\n    config.EnablePerformanceTracking = true;\n});\n\n// Configure data logging features\nLogManager.ConfigureDataLogging(config =\u003e \n{\n    config.EnableDataChangeTracking = true;\n    config.MaxComparisonDepth = 3;\n    config.IncludeSensitivePropertiesInChanges = false;\n    config.LogBeforeState = false;\n    config.LogAfterState = false;\n    config.DataChangeLogLevel = LogLevel.Info;\n});\n```\n\n## Implementation Details\n\nAnnotationLogger uses several advanced C# features:\n\n- **Expression Trees**: For method interception and parameter extraction\n- **Reflection**: For attribute discovery and parameter information\n- **AsyncLocal\u003cT\u003e**: For correlation ID propagation across async contexts\n- **Stopwatch**: For precise execution time measurement\n- **ReaderWriterLockSlim**: For thread-safe file logging\n- **ConcurrentDictionary/ConcurrentBag**: For thread-safe performance tracking\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frpdevjesco%2Fannotationlogframework","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frpdevjesco%2Fannotationlogframework","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frpdevjesco%2Fannotationlogframework/lists"}