Skip to content

Instantly share code, notes, and snippets.

@lukeschafer
Created July 18, 2014 04:23
Show Gist options
  • Save lukeschafer/d8c23582f0de28c38540 to your computer and use it in GitHub Desktop.
Save lukeschafer/d8c23582f0de28c38540 to your computer and use it in GitHub Desktop.
Serilog enricher + nimbus interceptor
public class MessageDataEnrichment
{
public string SessionId { get; set; }
}
public class MessageDataEnricher : ILogEventEnricher
{
public MessageDataEnricher()
{
CallContext.LogicalSetData(MessageDataEnricher.CallContextIdent, new MessageDataEnrichment());
}
public static string CallContextIdent = "MessageDataEnrichment_LCC";
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
var enrichment = CallContext.LogicalGetData(CallContextIdent) as MessageDataEnrichment;
if (enrichment != null)
{
logEvent.AddOrUpdateProperty(propertyFactory.CreateProperty("SessionId", enrichment.SessionId));
}
}
}
public class LoggableMessageDataInterceptor : InboundInterceptor
{
public string SessionId { get; private set; }
public LoggableMessageDataInterceptor()
{
SessionId = "";
}
public void SetSessionId(string sessionId)
{
var enrichment = CallContext.LogicalGetData(MessageDataEnricher.CallContextIdent) as MessageDataEnrichment;
if (enrichment == null)
{
enrichment = new MessageDataEnrichment();
CallContext.LogicalSetData(MessageDataEnricher.CallContextIdent, enrichment);
}
enrichment.SessionId = SessionId = sessionId ?? "";
}
public async override Task OnRequestHandlerExecuting<TBusRequest, TBusResponse>(IBusRequest<TBusRequest, TBusResponse> busRequest, BrokeredMessage brokeredMessage)
{
SetSessionId(brokeredMessage.SessionId);
}
public async override Task OnEventHandlerExecuting<TBusEvent>(TBusEvent busEvent, BrokeredMessage brokeredMessage)
{
SetSessionId(brokeredMessage.SessionId);
}
public async override Task OnCommandHandlerExecuting<TBusCommand>(TBusCommand busCommand, BrokeredMessage brokeredMessage)
{
SetSessionId(brokeredMessage.SessionId);
}
}
@lukeschafer
Copy link
Author

This is related to the following discussion: https://groups.google.com/forum/#!topic/serilog/FEvuVBAY5vI

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment