我在我的 ASP.NET Core 中使用 .NET 6 Web API 设置了带有 MongoDB 接收器的 Serilog,日志工作,因为我的数据库集合中有文档,但只有基本信息在错误时被保存,自定义字段仅保存在信息级别日志中。我希望它只记录错误并包含额外的字段。
在服务中
Log.Logger = new LoggerConfiguration()
.WriteTo.MongoDB(
database: myMongoDatabase,
restrictedToMinimumLevel: LogEventLevel.Error,
collectionName: "error_logs",
period: TimeSpan.FromSeconds(30))
.CreateLogger();
builder.Host.UseSerilog();
app.UseSerilogRequestLogging(x =>
{
x.IncludeQueryInRequestPath = true;
x.GetLevel = (httpContext, elapsed, ex) => LogEventLevel.Error;
x.Logger = Log.Logger;
x.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
if (httpContext.Request.ContentType is "x-www-form-urlencoded")
diagnosticContext.Set("RequestForm", httpContext.Request.Form);
diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
};
});