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
<PackageReference Include="Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore" Version="1.0.0" />
<PackageVersion Include="Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore" Version="1.0.0" />
<PackageReference Include="Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore" />
paket add Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore --version 1.0.0
#r "nuget: Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore, 1.0.0"
#:package Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore@1.0.0
#addin nuget:?package=Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore&version=1.0.0
#tool nuget:?package=Pro.Volo.Abp.Logging.Serilog.EntityFrameworkCore&version=1.0.0
ABP Serilog Logging Module
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 keyTimestamp(DateTime) - When the log was createdLevel(string) - Log level (Verbose, Debug, Information, Warning, Error, Fatal)Message(string) - Rendered log messageMessageTemplate(string) - Message template for structured loggingException(string) - Exception details if presentProperties(string) - Additional properties as JSON
User Context:
UserId(Guid?) - ID of the authenticated userUserName(string) - UsernameTenantId(Guid?) - Tenant ID for multi-tenant applications
HTTP Request Context:
CorrelationId(string) - Correlation ID for request tracingRequestPath(string) - HTTP request pathHttpMethod(string) - HTTP method (GET, POST, etc.)StatusCode(int?) - HTTP status codeClientIp(string) - Client IP addressUserAgent(string) - User agent stringApplicationName(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
Log Levels: Use appropriate log levels
Verbose/Debug: Development onlyInformation: General application flowWarning: Unexpected but handled situationsError: Errors and exceptionsFatal: Critical failures
Database Logging: Set
MinimumLeveltoWarningorErrorto avoid excessive database writesRetention: Configure
RetentionDaysandRetainedFileCountLimitto manage disk spaceStructured Logging: Use message templates with parameters instead of string interpolation
Correlation IDs: Use for tracing requests across microservices
Troubleshooting
Logs not appearing in database
- Ensure
EnableDatabaseLoggingis set totrue - Check that the migration was applied
- Verify the
MinimumLevelfor database logging - Check for exceptions in console output
High database load
- Increase
BatchSizeandFlushIntervalSeconds - Raise
MinimumLeveltoWarningorError - 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 | Versions 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. |
-
net8.0
- Pro.Volo.Abp.Logging.Serilog (>= 1.0.0)
- Serilog.Sinks.PeriodicBatching (>= 5.0.0)
- Volo.Abp.EntityFrameworkCore (>= 8.3.0)
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 |