0
votes

I am using MassTransit 3.5.7. I add the correlation ids before starting the bus:

MessageCorrelation.UseCorrelationId<ICustomerRegistered>(x => x.CustomerGuid);
MessageCorrelation.UseCorrelationId<ICustomerUpdated>(x => x.Customer.Guid);
MessageCorrelation.UseCorrelationId<IOrderPaid>(x => x.OrderGuid);
MessageCorrelation.UseCorrelationId<IOrderPaymentAuthorized>(x => x.OrderGuid);
MessageCorrelation.UseCorrelationId<IOrderPlaced>(x => x.Order.OrderGuid);
MessageCorrelation.UseCorrelationId<IOrderRefunded>(x => x.OrderGuid);

I use Serliog 2.5.0 for logging:

Bus.Factory.CreateUsingAzureServiceBus(serviceBus =>
{
    serviceBus.UseSerilog();
    ...
}

I can see that the CorrelationId is added to the message headers, but it's not added as a custom property to the logs.

What do I need to do in order to log the CorrelationId for all logged messages?

UPDATE:

I implemented a Serilog enricher and a MassTransit custom middleware like here, but the correlation id is only logged in the received (consumed) messages. It is not logged when publishing a message. Does anyone know how can I log the correlation id when publishing a message?

2
I'm not too familiar with Mass Transit. But I looked through their Serilog integration code and it didn't seem to provide any method of capturing the correlation ID. Perhaps you could write some custom middleware that grabs the correlation ID and uses enrichment to add the correlation ID to the logged event? - mason
Ah, it appears someone has done just that. - mason
@mason, thanks for the help. I found that gist and tried to implement it, but I think he is trying to solve a different problem. He is not getting the CorrelationId set in MassTransit, but he is setting a custom Guid that comes from the http request (actually Guid.NewGuid() in the code). I need to use the CorrelationId set in MassTransit. - Marius Stănescu
Hmm .. after looking some more at the code, I think it might be what I need. I will try to implement it again tomorrow. Thanks again. - Marius Stănescu
@mason I tried to implement the code from the gist, but the correlation id is added only to the consumed messages. It is not added to the published messages. I called the UseSeriLogEnricher method on the service bus configuration, not only on the receive endpoint, but I still get the correlation id only on the consumed messages. Any ideas? - Marius Stănescu

2 Answers

2
votes

You can Achieve this quite easily, and you are correct, it's with your own middleware.

I did that just that in this example. Now I am using LibLog (hence you will see LogProvider). But if you are referencing SeriLog directly, then you can simply do LogContext.PushProperty(...), and you will still get the same effect

1
votes

You can do it in a custom masstransit filter. if you set up a filter

cfg.ConfigureSend(c => c.UseSendFilter(new YourSendFilter()));

or for publish

cfg.ConfigurePublish(c => c.UseSendFilter(new YourSendFilter()));