在使用Serilog进行日志记录时,我无法将用户添加到我在PostgreSQL中创建的列中

jfewjypa  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(1)|浏览(143)

我正在通过下面的LoggerConfiguration创建一个自定义列。然后,使用中间件和我编写的UsernameColumnWriter类,我想在此列中打印发出请求时在PostgreSQL上登录的用户的名称。表和列正在形成,没有任何问题。但是,当我发出请求时,user_name列仍然为空,尽管创建了日志记录。
Serilog配置:

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()
.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;
    }
}
deikduxw

deikduxw1#

您希望使用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();

相关问题