如何限制EF Core命令文本记录通过Serilog



如何限制命令文本大小使用EFCore日志与Serilog?(和Serilog MS日志扩展)

Program.cs

int commandTextMaxLength = 300;
IHostBuilder builder = Host.CreateDefaultBuilder(args)
.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Destructure.ByTransforming<CommandEventData>(
logData => logData.Command?.CommandText?.Length > commandTextMaxLength ? 
new {
//logData.Connection,
Command = new
{
IsTrucated = true,
CommandText = logData.Command.CommandText.Substring(0, commandTextMaxLength) + "...",
logData.Command.CommandTimeout,
logData.Command.CommandType,
logData.Command.Parameters,
//logData.Command.Site
//logData.Command.UpdatedRowSource
},
logData.Context,
logData.ExecuteMethod,
logData.CommandId,
logData.ConnectionId,
logData.IsAsync,
logParameterValues=false,
logData.StartTime,
logData.CommandSource
}
: logData)
// optional .Enrich.FromLogContext()
// optional .Enrich.WithProcessId()
.WriteTo.Console()
.ConfigureLogging(builder => builder.AddSerilog())
;

EntityFrameworkCoreCommandTextDestructurePolicy.cs

// in Program.cs
// .Destructure.With<EntityFrameworkCoreCommandTextDestructurePolicy>()
public class EntityFrameworkCoreCommandTextDestructurePolicy : Serilog.Core.IDestructuringPolicy
{
public static int MaxSqlText { get; set; } = 300;
public bool TryDestructure(
object value
, Serilog.Core.ILogEventPropertyValueFactory propertyValueFactory
, out Serilog.Events.LogEventPropertyValue result
)
{
if (value is Microsoft.EntityFrameworkCore.Diagnostics.CommandEventData d && d.Command?.CommandText?.Length > MaxSqlText)
{
var newObj = new {
Command = new {
CommandText = d.Command.CommandText = d.Command.CommandText.Substring(0, MaxSqlText) + "..."
}
};
result = propertyValueFactory.CreatePropertyValue(newObj, destructureObjects: true);
return true;
}
result = null;
return false;
}
}

最新更新