Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore 1.0.0

dotnet add package Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore --version 1.0.0
                    
NuGet\Install-Package Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore -Version 1.0.0
                    
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="Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore" />
                    
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 Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore --version 1.0.0
                    
#r "nuget: Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore, 1.0.0"
                    
#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 Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore@1.0.0
                    
#: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=Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore&version=1.0.0
                    
Install as a Cake Tool

ABP Serilog Logging Module

NuGet License: MIT

A comprehensive, production-ready ABP module for structured logging with Serilog. Provides database and file logging with automatic user context enrichment, HTTP request tracking, and correlation ID support.

Features

Database Logging - Store logs in your application's database with batching support
File Logging - Configurable file logging with rolling policies and JSON formatting
User Context Enrichment - Automatically capture UserId, UserName, Email, and TenantId
HTTP Request Tracking - Log request path, method, IP address, user agent, and status codes
Correlation IDs - Trace related log entries across requests
Multi-Tenancy Support - Full support for ABP's multi-tenancy features
Performance Optimized - Asynchronous batching for minimal performance impact
Extensible - Easy to add custom enrichers and sinks

Installation

Install the NuGet packages:

# Core module (required)
dotnet add package Volo.Abp.Logging.Serilog

# Entity Framework Core integration (optional, for database logging)
dotnet add package Volo.Abp.Logging.Serilog.EntityFrameworkCore

Quick Start

1. Add Module Dependencies

Add the module dependencies to your ABP module:

[DependsOn(
    typeof(AbpLoggingSerilogModule),
    typeof(AbpLoggingSerilogEntityFrameworkCoreModule) // If using database logging
)]
public class YourModule : AbpModule
{
    // ...
}

2. Configure DbContext (For Database Logging)

Add the LogEntry entity to your DbContext:

using Volo.Abp.Logging.Serilog.EntityFrameworkCore;

public class YourDbContext : AbpDbContext<YourDbContext>
{
    public DbSet<LogEntry> SerilogLogs { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        // Configure the LogEntry entity
        builder.ConfigureAbpLoggingSerilog();
    }
}

3. Add Migration

Create and apply a migration to add the logs table:

dotnet ef migrations add AddSerilogLogging
dotnet ef database update

4. Configure appsettings.json

Add configuration to your appsettings.json:

{
  "Serilog": {
    "Abp": {
      "EnableDatabaseLogging": true,
      "EnableFileLogging": true,
      "EnableUserContextEnrichment": true,
      "EnableHttpContextEnrichment": true,
      "EnableRequestLogging": true,
      "MinimumLevel": "Information",
      "File": {
        "Path": "Logs/logs.txt",
        "RollingInterval": "Day",
        "FileSizeLimitBytes": 10485760,
        "RetainedFileCountLimit": 31,
        "OutputFormat": "Json",
        "MinimumLevel": "Information"
      },
      "Database": {
        "MinimumLevel": "Warning",
        "BatchSize": 50,
        "FlushIntervalSeconds": 5,
        "TableName": "SerilogLogs",
        "EnableAutoCleanup": false,
        "RetentionDays": 30
      }
    }
  }
}

Configuration Options

Main Options (AbpSerilogOptions)

Property Type Default Description
EnableDatabaseLogging bool false Enable database logging
EnableFileLogging bool true Enable file logging
EnableUserContextEnrichment bool true Add user context to logs
EnableHttpContextEnrichment bool true Add HTTP request context to logs
EnableRequestLogging bool true Enable request logging middleware
MinimumLevel string "Information" Minimum log level
ApplicationName string null Application name for logs

File Logging Options (AbpSerilogFileOptions)

Property Type Default Description
Path string "Logs/logs.txt" Log file path
RollingInterval string "Day" Rolling interval (Infinite, Year, Month, Day, Hour, Minute)
FileSizeLimitBytes long? 10485760 Max file size (10MB)
RetainedFileCountLimit int? 31 Number of files to retain
OutputFormat string "Json" Output format (Text, Json, CompactJson)
MinimumLevel string "Information" Minimum log level for files
Buffered bool true Enable buffered writing
FlushToDiskIntervalSeconds int 10 Flush interval in seconds

Database Logging Options (AbpSerilogDatabaseOptions)

Property Type Default Description
MinimumLevel string "Warning" Minimum log level for database
BatchSize int 50 Batch size for writing
FlushIntervalSeconds int 5 Flush interval in seconds
TableName string "SerilogLogs" Database table name
SchemaName string null Database schema name
EnableAutoCleanup bool false Enable automatic log cleanup
RetentionDays int 30 Days to retain logs
IncludeProperties bool true Include additional properties

Usage Examples

Basic Logging

public class MyService : ITransientDependency
{
    private readonly ILogger<MyService> _logger;

    public MyService(ILogger<MyService> logger)
    {
        _logger = logger;
    }

    public async Task DoSomethingAsync()
    {
        _logger.LogInformation("Processing started");
        
        try
        {
            // Your code here
            _logger.LogInformation("Processing completed successfully");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Processing failed");
            throw;
        }
    }
}

Structured Logging

_logger.LogInformation(
    "User {UserId} performed {Action} on {EntityType} with ID {EntityId}",
    userId,
    "Update",
    "Product",
    productId
);

Querying Logs from Database

public class LogQueryService : ITransientDependency
{
    private readonly IRepository<LogEntry, Guid> _logRepository;

    public LogQueryService(IRepository<LogEntry, Guid> logRepository)
    {
        _logRepository = logRepository;
    }

    public async Task<List<LogEntry>> GetRecentErrorsAsync()
    {
        return await _logRepository
            .Where(x => x.Level == "Error" && x.Timestamp > DateTime.UtcNow.AddHours(-24))
            .OrderByDescending(x => x.Timestamp)
            .Take(100)
            .ToListAsync();
    }

    public async Task<List<LogEntry>> GetUserLogsAsync(Guid userId)
    {
        return await _logRepository
            .Where(x => x.UserId == userId)
            .OrderByDescending(x => x.Timestamp)
            .ToListAsync();
    }
}

Log Entry Schema

The LogEntry entity includes the following properties:

Core Properties:

  • Id (Guid) - Primary key
  • Timestamp (DateTime) - When the log was created
  • Level (string) - Log level (Verbose, Debug, Information, Warning, Error, Fatal)
  • Message (string) - Rendered log message
  • MessageTemplate (string) - Message template for structured logging
  • Exception (string) - Exception details if present
  • Properties (string) - Additional properties as JSON

User Context:

  • UserId (Guid?) - ID of the authenticated user
  • UserName (string) - Username
  • TenantId (Guid?) - Tenant ID for multi-tenant applications

HTTP Request Context:

  • CorrelationId (string) - Correlation ID for request tracing
  • RequestPath (string) - HTTP request path
  • HttpMethod (string) - HTTP method (GET, POST, etc.)
  • StatusCode (int?) - HTTP status code
  • ClientIp (string) - Client IP address
  • UserAgent (string) - User agent string
  • ApplicationName (string) - Application name

Extensibility

Creating a Custom Enricher

using Serilog.Core;
using Serilog.Events;
using Volo.Abp.DependencyInjection;

public class CustomEnricher : ILogEventEnricher, ITransientDependency
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        logEvent.AddPropertyIfAbsent(
            propertyFactory.CreateProperty("CustomProperty", "CustomValue")
        );
    }
}

Then register it in your module:

public override void ConfigureServices(ServiceConfigurationContext context)
{
    context.Services.AddTransient<CustomEnricher>();
    
    // Add to Serilog configuration
    Log.Logger = new LoggerConfiguration()
        .Enrich.With<CustomEnricher>()
        // ... other configuration
        .CreateLogger();
}

Performance Considerations

  • Database Logging: Uses batching by default (50 logs per batch, 5-second flush interval) to minimize database calls
  • File Logging: Uses async buffered writing with configurable flush intervals
  • Enrichers: Lightweight and only execute when logs are actually written
  • Middleware: Minimal overhead, can be disabled if not needed

Best Practices

  1. Log Levels: Use appropriate log levels

    • Verbose/Debug: Development only
    • Information: General application flow
    • Warning: Unexpected but handled situations
    • Error: Errors and exceptions
    • Fatal: Critical failures
  2. Database Logging: Set MinimumLevel to Warning or Error to avoid excessive database writes

  3. Retention: Configure RetentionDays and RetainedFileCountLimit to manage disk space

  4. Structured Logging: Use message templates with parameters instead of string interpolation

  5. Correlation IDs: Use for tracing requests across microservices

Troubleshooting

Logs not appearing in database

  1. Ensure EnableDatabaseLogging is set to true
  2. Check that the migration was applied
  3. Verify the MinimumLevel for database logging
  4. Check for exceptions in console output

High database load

  1. Increase BatchSize and FlushIntervalSeconds
  2. Raise MinimumLevel to Warning or Error
  3. Consider using file logging for verbose logs

License

This project is licensed under the MIT License.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

For issues and questions, please use the GitHub issue tracker.

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
1.0.0 292 12/18/2025