首页 > 解决方案 > AspNet Core Serilog SQL 自定义列不起作用

问题描述

我已经使用 dotnet 3.1 在我的 ASP.NET Core MVC Web 应用程序中设置了 SeriLog,并添加了几个额外的列。尝试自动填充 UserName 不起作用。其他一切正常。我正在使用 Microsoft.Extensions.Logging ILogger 将我的记录器注入控制器中。不能使用 LogContext 自动设置此属性,还是我必须像这样显式调用每个日志条目的对象(“由 {UserName} 记录的信息”,User.Identity.Name)。

这是我的 Program.cs

public static void Main(string[] args)
    {
        // Boilerplate code: https://github.com/serilog/serilog-aspnetcore/blob/dev/samples/Sample/Program.cs
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .CreateBootstrapLogger();

        Log.Information("Starting up!");

        try
        {
            CreateHostBuilder(args).Build().Run();
            Log.Information("Stopped cleanly");
        }
        catch (System.Exception ex)
        {
            Log.Fatal(ex, "An unhandled exception occured during bootstrapping");
            throw;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        return Host.CreateDefaultBuilder(args)
                    .UseSerilog((context, services, configuration) => configuration
                        .ReadFrom.Configuration(context.Configuration)
                        .ReadFrom.Services(services)
                        .Enrich.FromLogContext()
                        .WriteTo.Console()
                        .WriteTo.MSSqlServer(
                            context.Configuration.GetConnectionString("FlightDelayDatabase"), 
                            sinkOptions: new MSSqlServerSinkOptions { TableName = "Log" }, null, null, 
                            LogEventLevel.Information, null, columnOptions: new ColumnOptions
                            {
                                AdditionalColumns = new Collection<SqlColumn>
                                {
                                   new SqlColumn("UserName", SqlDbType.NVarChar)
                                }
                            }, null, null))
                    .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
    }

在我的 StartUp.cs 中,我在 app.UseAuthorization() 和 app.UseEndpoints() 之间有这个

app.Use(async (context, next) =>
        {
            var userName = context.User.Identity.IsAuthenticated ? context.User.Identity.Name : "Guest"; //Gets user Name from user Identity  
            LogContext.PushProperty("Username", userName); //Push user in LogContext;  
            await next(); 
        });

使用 Serilog.AspNetCore 4.1.0 和 Serilog.Sinks.MSSqlServer 5.6.1。

SQL 数据库日志

这是架构

CREATE TABLE [dbo].[Log](  
[Id] [int] IDENTITY(1,1) NOT NULL,  
[Message] [nvarchar](max) NULL,  
[MessageTemplate] [nvarchar](max) NULL,  
[Level] [nvarchar](128) NULL,  
[TimeStamp] [datetimeoffset](7) NOT NULL,  
[Exception] [nvarchar](max) NULL,  
[Properties] [xml] NULL,  
[LogEvent] [nvarchar](max) NULL,  
[UserName] [nvarchar](200) NULL,  
[IP] [varchar](200) NULL,  

...

从数据库这里有一个来自属性 xml 列的日志条目。 XML

标签: c#asp.net-coreserilog

解决方案


推荐阅读