我正在通过下面的 LoggerConfiguration 创建自定义列。然后,使用我编写的中间件和 UsernameColumnWriter 类,我想在发出请求时在此列中打印 Postgresql 上登录用户的名称。表格和列正在形成,没有任何问题。但是,当我发出请求时,尽管创建了日志记录,但 user_name 列仍为空。
Serilog 配置:
Logger log = new LoggerConfiguration()
.WriteTo.PostgreSQL(builder.Configuration.GetConnectionString("ConnectionString"),
"Logs",
needAutoCreateTable: true,
columnOptions: new Dictionary<string, ColumnWriterBase>
{
{"message", new RenderedMessageColumnWriter(NpgsqlDbType.Text)},
{"message_template", new MessageTemplateColumnWriter(NpgsqlDbType.Text)},
{"level", new LevelColumnWriter(true , NpgsqlDbType.Varchar)},
{"time_stamp", new TimestampColumnWriter(NpgsqlDbType.Timestamp)},
{"exception", new ExceptionColumnWriter(NpgsqlDbType.Text)},
{"log_event", new LogEventSerializedColumnWriter(NpgsqlDbType.Json)},
{"user_name", new UsernameColumnWriter()}
})
.WriteTo.Debug()
.WriteTo.Console()
.MinimumLevel.Information()
.CreateLogger();
builder.Host.UseSerilog(log);
中间件:
app.UseSerilogRequestLogging();
app.UseHttpLogging();
app.UseAuthentication();
app.UseAuthorization();
app.Use(async (context, next) => {
var username = context.User?.Identity?.IsAuthenticated != null || true ?
context.User.Identity.Name : null;
LogContext.PushProperty("user_name", username);
await next();
});
我的班级:
public class UsernameColumnWriter : ColumnWriterBase {
public UsernameColumnWriter() : base(NpgsqlDbType.Varchar) {
}
public override object GetValue(LogEvent logEvent, IFormatProvider formatProvider = null) {
var (username, value) = logEvent.Properties.FirstOrDefault(p => p.Key == "user_name");
return value?.ToString() ?? null;
}
}
您想使用
LogContext
中的属性,但您的配置缺少所需部分:
...
.Enrich.FromLogContext()
...
所以您的最终配置应如下所示:
Logger log = new LoggerConfiguration()
.WriteTo.PostgreSQL(builder.Configuration.GetConnectionString("3pmConnectionString"),
"Logs",
needAutoCreateTable: true,
columnOptions: new Dictionary<string, ColumnWriterBase>
{
{"message", new RenderedMessageColumnWriter(NpgsqlDbType.Text)},
{"message_template", new MessageTemplateColumnWriter(NpgsqlDbType.Text)},
{"level", new LevelColumnWriter(true , NpgsqlDbType.Varchar)},
{"time_stamp", new TimestampColumnWriter(NpgsqlDbType.Timestamp)},
{"exception", new ExceptionColumnWriter(NpgsqlDbType.Text)},
{"log_event", new LogEventSerializedColumnWriter(NpgsqlDbType.Json)},
{"user_name", new UsernameColumnWriter()}
})
.WriteTo.Debug()
.WriteTo.Console()
.MinimumLevel.Information()
.Enrich.FromLogContext() // <--
.CreateLogger();