I'd like to log every message that i consume in MassTransit. Is there a way to implement global interceptor where i could handle income message or achieve that using configuration?
My current config looks like this:
BusFactory = Bus.Factory.CreateUsingRabbitMq(cfg =>
{
var host = cfg.Host(new Uri(AppSettings.RmqConnectionString), h => { });
cfg.UseNLog();
cfg.ReceiveEndpoint(host, RmqPropertyKeys.CallbackQueue, e=> e.LoadFrom(container));
});
The documentation includes an example middleware filter which does exactly that, logs on every message that is delivered to a consumer.
http://docs.masstransit-project.com/en/latest/middleware/custom.html
You can also use the built-in LogFilter
if you like:
cfg.UseLog(Console.Out, (context,logContext) => $"Format your log message");
Another way is to use ConsumeObserver
.
Implement the interface IConsumeObserver:
public class ConsumeObserver : IConsumeObserver
{
private readonly ILogger<ConsumeObserver> _logger;
public ConsumeObserver(ILogger<ConsumeObserver> logger)
{
_logger = logger;
}
public Task ConsumeFault<T>(ConsumeContext<T> context, Exception exception) where T : class
{
//use _logger
return Task.CompletedTask;
}
public Task PostConsume<T>(ConsumeContext<T> context) where T : class
{
//use _logger
return Task.CompletedTask;
}
public Task PreConsume<T>(ConsumeContext<T> context) where T : class
{
//use _logger
return Task.CompletedTask;
}
}
Then connect your observer:
busControl.ConnectConsumeObserver(consumeObserver);
You can also use the message audit mechanism