在我的网站中,我正在集成 Serilog 以将错误记录到自定义接收器。日志记录通过 LogContext 进行了丰富,其中需要传递一些自定义属性。如果我使用 Log.Information() ,它会带着 LogEvent 中的属性到达我的接收器。所以这很有效。
主要目的是将日志系统与异常处理程序中间件结合起来。因此,在异常处理程序中,错误被捕获,该错误是从控制器方法抛出的。无论我将 _logger.Log() 放在异常处理程序中的任何位置,接收器中都没有可用的自定义属性。调试时,它在进入 Sink 之前传递了 LogContextFilter,但未找到过滤器的属性。
有人有什么想法吗?
Startup
Log.Logger = new LoggerConfiguration()
.WriteTo.PasSink(new SerLogServiceClient.SerLogServiceClient(new SerLogServiceClientOptions()))
.Enrich.FromLogContext()
.CreateLogger();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddMvcOptions(mo =>
{
mo.Filters.Add(typeof(LogContextFilter));
});
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<LogContextMiddleware>();
app.UseErrorHandler(o =>
{
o.ExceptionHandlingPath = "/Home/Error";
o.Context = ExceptionHandler.Context.MVC;
});
//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "Content")),
RequestPath = "/Content"
});
app.UseAuthentication();
app.UseSession();
//app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
日志上下文过滤器
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
using (LogContext.Push(
new PropertyEnricher("UserCode", context.HttpContext.User.Claims.FirstOrDefault(s => s.ToString().StartsWith("UserCode"))?.Value),
new PropertyEnricher("Test", "Will this go through?")))
{
await next.Invoke();
}
}
异常处理中间件
public async Task Invoke(HttpContext context)
{
try
{
await _next.Invoke(context);
}
catch (HttpRequestException hex)
{
//check response naar reynaersexception??
//deserialize naar re
throw new NotSupportedException(); //als test
}
catch (Exception ex)
{
if (context.Response.HasStarted)
{
throw ex;
}
_logger.LogError(ex.Message);
var originalPath = context.Request.Path;
try
{
if (_options.Context == Context.MVC)
{
context.Response.Clear();
context.Response.StatusCode = 500;
context.Response.OnStarting(Callback, context.Response);
//set features
var exceptionHandlerFeature = new ReynaersExceptionHandlerFeature()
{
Error = ex,
Path = context.Request.Path.Value,
};
context.Features.Set<IExceptionHandlerFeature>(exceptionHandlerFeature);
context.Features.Set<IExceptionHandlerPathFeature>(exceptionHandlerFeature);
//continue lifecycle with updated context
if (_options.ExceptionHandlingPath.HasValue)
{
context.Request.Path = _options.ExceptionHandlingPath;
}
await _next.Invoke(context);
}
}
catch (Exception ex2)
{
// Suppress secondary exceptions, re-throw the original.
Log.Error(ex2.Message);
context.Request.Path = originalPath;
throw ex;
}
}
}