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

问题描述 投票:0回答:1

在 Serilog 中使用 EFCore 日志记录时如何限制 commandText 大小? (和 Serilog MS 日志扩展。)

c# entity-framework-core serilog
1个回答
0
投票

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())
;
© www.soinside.com 2019 - 2024. All rights reserved.