While logging with Serilog, I cannot add users to the column I created in Postgresql

huangapple go评论126阅读模式
英文:

While logging with Serilog, I cannot add users to the column I created in Postgresql

问题

我正在通过以下的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;
    }
}
英文:

I am creating a custom column via LoggerConfiguration below. Then, using the middleware and the UsernameColumnWriter class I wrote, I want to print the name of the logged in user on Postgresql when the request is made, in this column. The table and column are forming without any problems. However, when I make a request, the user_name column remains empty, although log records are created.

Serilog configurations:

Logger log = new LoggerConfiguration()
.WriteTo.PostgreSQL(builder.Configuration.GetConnectionString(&quot;ConnectionString&quot;),
    &quot;Logs&quot;,
    needAutoCreateTable: true,
    columnOptions: new Dictionary&lt;string, ColumnWriterBase&gt;
    {
        {&quot;message&quot;, new RenderedMessageColumnWriter(NpgsqlDbType.Text)},
        {&quot;message_template&quot;, new MessageTemplateColumnWriter(NpgsqlDbType.Text)},
        {&quot;level&quot;, new LevelColumnWriter(true , NpgsqlDbType.Varchar)},
        {&quot;time_stamp&quot;, new TimestampColumnWriter(NpgsqlDbType.Timestamp)},
        {&quot;exception&quot;, new ExceptionColumnWriter(NpgsqlDbType.Text)},
        {&quot;log_event&quot;, new LogEventSerializedColumnWriter(NpgsqlDbType.Json)},
        {&quot;user_name&quot;, new UsernameColumnWriter()}
    })
.WriteTo.Debug()
.WriteTo.Console()
.MinimumLevel.Information()
.CreateLogger();

builder.Host.UseSerilog(log);

Middleware:

app.UseSerilogRequestLogging();
app.UseHttpLogging();

app.UseAuthentication();
app.UseAuthorization();

app.Use(async (context, next) =&gt; {
    var username = context.User?.Identity?.IsAuthenticated != null || true ? 
        context.User.Identity.Name : null;
    LogContext.PushProperty(&quot;user_name&quot;, username);
    await next();
});

My Class:

    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 =&gt; p.Key == &quot;user_name&quot;);
        return value?.ToString() ?? null;
    }
}

答案1

得分: 1

.Enrich.FromLogContext() // &lt;--
.Enrich.FromLogContext() // &lt;--
英文:

You want to use properties from LogContext but your configuration misses the required section :

...
.Enrich.FromLogContext()
...

So your final configuration should look like the below :

Logger log = new LoggerConfiguration()
.WriteTo.PostgreSQL(builder.Configuration.GetConnectionString(&quot;3pmConnectionString&quot;),
    &quot;Logs&quot;,
    needAutoCreateTable: true,
    columnOptions: new Dictionary&lt;string, ColumnWriterBase&gt;
    {
        {&quot;message&quot;, new RenderedMessageColumnWriter(NpgsqlDbType.Text)},
        {&quot;message_template&quot;, new MessageTemplateColumnWriter(NpgsqlDbType.Text)},
        {&quot;level&quot;, new LevelColumnWriter(true , NpgsqlDbType.Varchar)},
        {&quot;time_stamp&quot;, new TimestampColumnWriter(NpgsqlDbType.Timestamp)},
        {&quot;exception&quot;, new ExceptionColumnWriter(NpgsqlDbType.Text)},
        {&quot;log_event&quot;, new LogEventSerializedColumnWriter(NpgsqlDbType.Json)},
        {&quot;user_name&quot;, new UsernameColumnWriter()}
    })
.WriteTo.Debug()
.WriteTo.Console()
.MinimumLevel.Information()
.Enrich.FromLogContext() // &lt;--
.CreateLogger();

huangapple
  • 本文由 发表于 2023年6月16日 15:24:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76487859.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定