Are Serilog enrichers - and LogEvent in particular - expected to be aware of properties pushed onto LogContext?
I have a property which is pushed onto the Serilog context:
using (LogContext.PushProperty(LoggingConstants.MyProperty, _myValue))
{
// ...
}
I also have a custom enricher registered which adds a property if it's not present, padding it to a specified length:
public class PaddedPropertyEnricher : ILogEventEnricher
{
private readonly string _propertyName;
private readonly int _maxLength;
public PaddedPropertyEnricher(string propertyName, int maxLength)
{
_propertyName = propertyName;
_maxLength = maxLength;
}
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
var property = propertyFactory.CreateProperty(_propertyName, new string(' ', _maxLength));
logEvent.AddPropertyIfAbsent(property);
}
}
and:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.Enrich.With(new PaddedPropertyEnricher(LoggingConstants.MyProperty, 3))
// etc.
The intent of this enricher is so log entries which don't contain the custom property don't result in columns in the the log entries becoming misaligned.
For example, it is intended to transform this:
2021-06-10 12:23:33.676 +12:00 [INF] [] First message without MyProperty
2021-06-10 12:23:33.677 +12:00 [DBG] [123] Second message with MyProperty
into this:
2021-06-10 12:23:33.676 +12:00 [INF] [ ] First message without MyProperty
2021-06-10 12:23:33.677 +12:00 [DBG] [123] Second message with MyProperty
However, this enricher isn't working. When the enricher is registered against the property I'm pushing onto the context, the value retrieved from LogEvent is always null - unless MyProperty is explicitly in the log message itself.
Is this a known limitation, or am I misusing enrichers?
This may be related to the issues encountered at Always log context data using serilog.