Skip to content

Instantly share code, notes, and snippets.

@ramonsmits
Last active May 16, 2018 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramonsmits/5c27ee0cff9e1230279bb247842bda60 to your computer and use it in GitHub Desktop.
Save ramonsmits/5c27ee0cff9e1230279bb247842bda60 to your computer and use it in GitHub Desktop.
NServiceBus log4net - Use NDC to show incoming message id
using System;
using System.Threading.Tasks;
using log4net;
using NServiceBus.Pipeline;
/// <summary>
/// Pushes the current message ID to the log4net NDC stack. When using a log4net conversation pattern containing `%ndc` then this value used ("%date [%-3thread] %-5level [%ndc] %logger - %message%newline").
/// </summary>
/// <example>
/// var pipeline = endpointConfiguration.Pipeline;
/// pipeline.Register(behavior: new AssignMessageIdtoLog4netNdcBehavior(), description: "Assigns the incoming message id to the log4net NDC.");
/// </example>
class AssignMessageIdtoLog4netNdcBehavior : Behavior<ITransportReceiveContext>
{
public override async Task Invoke(ITransportReceiveContext context, Func<Task> next)
{
// Do not use NDC.Push, not compatible with async/await
using (LogicalThreadContext.Stacks["NDC"].Push(context.Message.MessageId))
{
await next().ConfigureAwait(false);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment