/

Entity Framework Core Integration

ByteHide Logger provides comprehensive logging for Entity Framework Core database operations, including queries, commands, transactions, and performance monitoring.

Installation

Install the Entity Framework Core integration package:

dotnet add package Bytehide.Logger.EntityFramework

Basic Configuration

Option 1: Service Registration

Register the service in Program.cs:

using Bytehide.Logger.EntityFramework.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Add ByteHide EF Core logging
builder.Services.AddBytehideEntityFrameworkLogging(options => {
    options.ProjectToken = "your-project-token";
});

// Register your DbContext with ByteHide logging
builder.Services.AddDbContext<ApplicationDbContext>((serviceProvider, options) => {
    options.UseSqlServer("your-connection-string")
           .UseBytehideLogging(serviceProvider);
});

Option 2: DbContext Configuration

Add logging directly in your DbContext:

using Bytehide.Logger.EntityFramework.Extensions;

public class ApplicationDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .UseSqlServer("your-connection-string")
            .UseBytehideLogging(); // Add this line
    }
}

Configuration Options

Basic Options

builder.Services.AddBytehideEntityFrameworkLogging(options => {
    // Required
    options.ProjectToken = "your-project-token";
    
    // Event Tracking
    options.CaptureQueryEvents = true;         // Log SELECT queries
    options.CaptureCommandEvents = true;       // Log INSERT/UPDATE/DELETE
    options.CaptureTransactionEvents = true;   // Log transactions
    options.CaptureConnectionEvents = false;   // Log connections (verbose)
    
    // Security
    options.IncludeParameterValues = false;    // Don't log parameter values
    options.SensitiveParameterPatterns = new[] {
        "password", "token", "secret", "key"
    };
    
    // Performance
    options.QueryExecutionThresholdMs = 100;   // Only log slow queries
    options.MaxSqlLength = 4000;               // Truncate long SQL
    
    options.LogLevel = LogLevel.Info;          // Minimum log level
});

File Logging

builder.Services.AddBytehideEntityFrameworkLogging(
    options => {
        options.ProjectToken = "your-project-token";
    },
    logSettings => {
        // Enable file logging
        logSettings.Persist = true;
        logSettings.FilePath = "logs/database.log";
        logSettings.RollingInterval = RollingInterval.Day;
    }
);

Features

Automatic Query Logging

// This query will be automatically logged
var users = await context.Users
    .Where(u => u.IsActive)
    .ToListAsync();

// Log output:
// [INFO] Database SELECT executed in 45ms
// SQL: SELECT [u].[Id], [u].[Name] FROM [Users] AS [u] WHERE [u].[IsActive] = @p0

Transaction Tracking

using var transaction = await context.Database.BeginTransactionAsync();
try
{
    context.Orders.Add(new Order { /* ... */ });
    await context.SaveChangesAsync();
    await transaction.CommitAsync();
}
catch
{
    await transaction.RollbackAsync();
    throw;
}

// Automatically logs:
// - Transaction started
// - Commands executed
// - Transaction committed/rolled back

Error Logging

try
{
    await context.SaveChangesAsync();
}
catch (DbUpdateException ex)
{
    // Exception automatically logged with SQL context
    throw;
}

Usage Examples

Monitoring Slow Queries

// Configure to only log queries slower than 500ms
builder.Services.AddBytehideEntityFrameworkLogging(options => {
    options.ProjectToken = "your-project-token";
    options.QueryExecutionThresholdMs = 500;
});

// Slow queries will be logged with WARNING level

Development vs Production

if (builder.Environment.IsDevelopment())
{
    // Log all queries in development
    builder.Services.AddBytehideEntityFrameworkLogging(options => {
        options.ProjectToken = "your-project-token";
        options.QueryExecutionThresholdMs = 0;
        options.LogLevel = LogLevel.Debug;
        options.IncludeParameterValues = true; // Use carefully
    });
}
else
{
    // Only log slow queries in production
    builder.Services.AddBytehideEntityFrameworkLogging(options => {
        options.ProjectToken = "your-project-token";
        options.QueryExecutionThresholdMs = 1000;
        options.LogLevel = LogLevel.Warn;
    });
}

Options Reference

OptionTypeDefaultDescription
ProjectTokenstringnullYour ByteHide project token
CaptureQueryEventsbooltrueLog SELECT queries
CaptureCommandEventsbooltrueLog INSERT/UPDATE/DELETE commands
CaptureTransactionEventsbooltrueLog transaction operations
CaptureConnectionEventsboolfalseLog connection events
IncludeParameterValuesboolfalseInclude parameter values in logs
SensitiveParameterPatternsstring[]["password", "token"]Patterns for parameters to mask
QueryExecutionThresholdMsint0Minimum query time to log (ms)
MaxSqlLengthint4000Maximum SQL length to log
LogLevelLogLevelInfoMinimum log level
ReplaceDefaultLoggerboolfalseReplace EF Core's default logger

Best Practices

  • Use QueryExecutionThresholdMs in production to only log slow queries
  • Keep IncludeParameterValues = false unless debugging specific issues
  • Disable CaptureConnectionEvents in high-traffic applications
  • Add sensitive parameter patterns for your specific use case

Next Steps

Previous
ASP.NET Framework