asp.net-core-webapi - How to push custom properties to Serilog’s LogContext without adding other context properties?
问题描述
In a .Net Core 2.2 API, I am trying to use Serilog for logging to SQL Server to take advantage of its structured logging capabilities. Besides the standard fields (Id, Timestamp, Level, Message, MessageTemplate, LogEvent), I need to capture the user’s name and IP address with every log entry. I have seen this post but I’d like to do this in one place so the developers don’t have to add it manually with each log statement. I have the following snippet in my Startup.cs
ctor:
public Startup(IConfiguration configuration)
{
_configuration = configuration;
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.Enrich.FromLogContext()
.Enrich.With<SerilogContextEnricher>()
.CreateLogger();
}
The .Enrich.FromLogContext()
call makes the static LogContext available for me to add my custom properties (username and IP address) in a custom middleware like so:
public class SerilogMiddleware
{
private static readonly ILogger Log = Serilog.Log.ForContext<SerilogMiddleware>();
private readonly RequestDelegate _next;
public SerilogMiddleware(RequestDelegate next)
{
this._next = next ?? throw new ArgumentNullException(nameof(next));
}
public async Task Invoke(HttpContext httpContext)
{
if (httpContext == null) throw new ArgumentNullException(nameof(httpContext));
// Get user info
var user = httpContext.User.FindFirst(ClaimTypes.Name)?.Value ?? "anonymous";
// Get client info
var client = httpContext.Connection.RemoteIpAddress.ToString() ?? "unknown";
// enrich LogContext with user info
using (LogContext.PushProperty("User", user))
using (LogContext.PushProperty("Client", client))
{
try
{
await _next(httpContext);
}
// Never caught, because LogException() returns false.
catch (Exception ex) when (LogException(httpContext, ex)) { }
}
}
private static bool LogException(HttpContext httpContext, Exception ex)
{
var logForContext = Log.ForContext("StackTrace", ex.StackTrace);
logForContext.Error(ex, ex.Message);
return false;
}
}
However, the .Enrich.FromLogContext()
call also adds ActionId, ActionName, RequestId, RequestPath and CorrelationId properties to the LogEvent field. I don’t want to bloat my log table with these 5 properties. My current solution is to enrich my logger with the below custom enricher that removes these properties from EventLog.
public class SerilogContextEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
logEvent.RemovePropertyIfPresent("ActionId");
logEvent.RemovePropertyIfPresent("ActionName");
logEvent.RemovePropertyIfPresent("RequestId");
logEvent.RemovePropertyIfPresent("RequestPath");
logEvent.RemovePropertyIfPresent("CorrelationId");
}
}
This all works fine but it seems silly to initially add these properties to the logger and then remove them afterwards. Does anyone know of a way to push custom properties to all log entries universally without this game of adding and removing unwanted properties?
解决方案
推荐阅读
- android - 为什么挂起的意图在从服务的通知中调用时不会启动活动
- javascript - 从输入标签向段落添加千位分隔符
- reactjs - 在 React 中从 2 个没有按钮的文本框中添加值
- julia - 如何在 Plots.jl 中旋转字体
- parsing - 如何正确解析十进制值?
- angular - 运行 Angular 项目显示错误为 angular-in-memory-web-api
- spring - springboot postgresql 创建无序数据
- sql - 根据SSRS中的负值和正值对条件进行排序
- python - 使VSCode python调试打印输出到终端
- python - django,如何处理带有外键的modelForm?