c# - 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。
这是架构
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,
...
解决方案
推荐阅读
- reactjs - Axios - 未处理的拒绝(TypeError):无法读取未定义的属性“数据”
- jquery - laravel 8 没有从 ajax 请求中获取数据
- python - 如何使用 python 多处理捕获 pi 相机图像
- python - 在 requirements.txt 之外安装一个包
- bash - 防止 terraform 函数“模板文件”输出 heredoc
- javascript - BrowserFS 起始文件路径指向本地文件夹
- git - Intellij Idea Git Log 中的这些行是什么意思?
- php - 同一页面上的联系表格 7 多个表单不适用于 ajax 提交
- java - 重构多个 || java中If语句中的&&条件
- vue.js - 当路由器在vue2中更改时,如何在页面顶部显示vuetify的v-progress-linear?