Fermion.ExceptionLog 0.0.1

The owner has unlisted this package. This could mean that the package is deprecated, has security vulnerabilities or shouldn't be used anymore.
dotnet add package Fermion.ExceptionLog --version 0.0.1
                    
NuGet\Install-Package Fermion.ExceptionLog -Version 0.0.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Fermion.ExceptionLog" Version="0.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Fermion.ExceptionLog" Version="0.0.1" />
                    
Directory.Packages.props
<PackageReference Include="Fermion.ExceptionLog" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Fermion.ExceptionLog --version 0.0.1
                    
#r "nuget: Fermion.ExceptionLog, 0.0.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Fermion.ExceptionLog@0.0.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Fermion.ExceptionLog&version=0.0.1
                    
Install as a Cake Addin
#tool nuget:?package=Fermion.ExceptionLog&version=0.0.1
                    
Install as a Cake Tool

Fermion.ExceptionLog

License Version

Fermion.ExceptionLog is a comprehensive exception handling and logging library for ASP.NET Core applications. It provides centralized exception handling, standardized error responses, and multi-target logging capabilities, all in one easy-to-use package.

Features

  • 🔄 Global exception middleware for centralized error handling
  • 🧩 Problem Details responses compliant with RFC 7807
  • 📊 Customized responses for different exception types
  • 📝 Multiple logging targets (Console, File, Database)
  • 🔍 Correlation ID and session tracking
  • ✅ FluentValidation integration for automatic validation
  • 🔄 Easy integration with Entity Framework Core

Installation

NuGet Package

Install the package via NuGet Package Manager:

Install-Package Fermion.ExceptionLog

Or via .NET CLI:

dotnet add package Fermion.ExceptionLog

Dependencies

This package requires the following dependencies:

  • .NET 8.0+
  • Fermion.EntityFramework.Core (>= 0.0.1)
  • AutoMapper.Extensions.Microsoft.DependencyInjection (>= 12.0.1)
  • FluentValidation.DependencyInjectionExtensions (>= 11.11.0)

Basic Usage

1. Service Configuration

Register the services in your Program.cs file:

// Add your DbContext
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// Register Fermion exception logging services
builder.Services.AddFermionExceptionLogServices<ApplicationDbContext>(options =>
{
    options.EnableConsoleLogging = true;       // Enable console logging
    options.EnableFileLogging = true;          // Enable file logging
    options.LogDirectory = "Logs/App";         // Custom log directory (optional)
});

// Add validation filter (optional)
builder.Services.AddControllers()
    .AddGlobalValidationFilter();

2. Middleware Configuration

Add the middleware in your Program.cs file (before other middleware!):

// Middleware pipeline
var app = builder.Build();

// Add ExceptionMiddleware before other middleware
app.ConfigureFermionExceptionMiddleware();

// Other middleware...
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

3. DbContext Configuration

Add the entity configuration in your ApplicationDbContext.cs:

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        
        // Configure based on your database provider
        // Options: PostgreSql, SqlServer, MySql
        builder.ApplyConfiguration(new AppExceptionLogConfiguration(DatabaseProviderTypes.PostgreSql));
    }
}

Advanced Usage

Using the Logger

Use the IAppLogger service to log at different levels:

public class ProductService
{
    private readonly IAppLogger<ProductService> _logger;

    public ProductService(IAppLogger<ProductService> logger)
    {
        _logger = logger;
    }

    public async Task<Product> GetProductByIdAsync(int id)
    {
        _logger.LogInformation($"Getting product with ID: {id}");
        
        try
        {
            var product = await _productRepository.GetByIdAsync(id);
            
            if (product == null)
            {
                _logger.LogWarning($"Product with ID {id} not found");
                throw new AppEntityNotFoundException("Product", id.ToString());
            }
            
            return product;
        }
        catch (Exception ex)
        {
            _logger.LogError("Error retrieving product", ex);
            throw;
        }
    }
}

Using Custom Exceptions

The library supports several custom exception types for different error scenarios:

// When an entity is not found
throw new AppEntityNotFoundException("Product", id.ToString());

// Authorization error
throw new AppUnauthorizedAccessException("You don't have permission to access this resource");

// Authentication error
throw new AppAuthenticationFailedException("Invalid credentials");

// Business logic errors
throw new AppBusinessException("Cannot complete the operation", "ORDER_ALREADY_SHIPPED");

// For validation errors, using validators is recommended

Querying Exception Logs

public class LogViewerService
{
    private readonly IAppExceptionLogAppService _logService;

    public LogViewerService(IAppExceptionLogAppService logService)
    {
        _logService = logService;
    }

    public async Task<IEnumerable<AppExceptionLogResponseDto>> GetLogsByCorrelationIdAsync(Guid correlationId)
    {
        var request = new GetListAppExceptionLogRequestDto
        {
            CorrelationId = correlationId,
            PageSize = 100
        };

        var result = await _logService.GetAppExceptionLogsFilteredAndPaginatedAsync(request);
        return result.Items;
    }
}

Error Responses

The middleware returns customized HTTP responses for different exception types:

Exception Type HTTP Status Code Description
AppValidationException 400 Request data failed validation
AppAuthenticationFailedException 401 Authentication error
AppUnauthorizedAccessException 403 Authorization error
AppEntityNotFoundException 404 Requested resource not found
AppBusinessException 500 Business rule violation
Other Exceptions 500 Unexpected internal server error

Example JSON response:

{
  "code": "404",
  "message": "Entity 'Product' with ID '42' was not found.",
  "detail": "The requested product might have been deleted or does not exist.",
  "correlationId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
}

Validation Integration

Fermion.ExceptionLog integrates with FluentValidation. It automatically catches validation errors and returns an appropriate response to the client:

// Define your DTO
public class CreateProductDto
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

// Add a validator
public class CreateProductDtoValidator : AbstractValidator<CreateProductDto>
{
    public CreateProductDtoValidator()
    {
        RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
        RuleFor(x => x.Price).GreaterThan(0);
    }
}

// It will be automatically validated in your controller
[HttpPost]
public async Task<IActionResult> CreateProduct(CreateProductDto dto)
{
    // If validation fails, AppValidationException is thrown
    // and caught by the middleware
    var product = await _productService.CreateProductAsync(dto);
    return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}

Log Sink Configuration

Fermion.ExceptionLog supports multiple log sinks that can be configured:

Console Logging

Console logs provide colorized output with emojis for better readability:

[2023-01-01 12:34:56] [Error] [ProductService]
  🔗 CorrelationId: 3fa85f64-5717-4562-b3fc-2c963f66afa6
  👤 CreatorId: 7fa85f64-5717-4562-b3fc-2c963f66afa6
  📝 Message: Error retrieving product
  ❌ Exception: Product with ID 42 was not found
     StackTrace: at MyApp.Services.ProductService...

File Logging

File logs are stored in the configured directory with a daily rotation:

--------------------------------------------------
📅 Timestamp   : 2023-01-01 12:34:56
⚡ Level       : Error
📁 Category    : ProductService
🔗 CorrelationId: 3fa85f64-5717-4562-b3fc-2c963f66afa6
👤 CreatorId   : 7fa85f64-5717-4562-b3fc-2c963f66afa6
📝 Message     : Error retrieving product
❌ Exception   : Product with ID 42 was not found
🔍 StackTrace  :
at MyApp.Services.ProductService...
--------------------------------------------------

Database Logging

Exceptions are automatically stored in the database and can be queried through the provided service layer.

Contributing

If you would like to contribute to this project, please fork the repository and submit a pull request. For any questions or suggestions, feel free to contact us through GitHub Issues.

License

This project is licensed under the MIT License. See the LICENSE file for more information.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated