Cante Ibanez
Cante Ibanez

Reputation: 331

In Audit.Net is there a way to use multiple output provider?

I tried setting up the configuration below however, I think only one of them is being used.

Is there a way to chain the two or is there any other way to use multiple output provider?

            Audit.Core.Configuration.Setup()
                .UseElasticsearch(config => config
                    .ConnectionSettings(new Uri(elasticUri))
                    .Index("sample-index")
                    .Id(ev => Guid.NewGuid()));

            Audit.Core.Configuration.Setup()
                .UseUdp(config => config
                    .RemoteAddress("127.0.0.1")
                    .RemotePort(6060));

Upvotes: 4

Views: 1427

Answers (1)

thepirat000
thepirat000

Reputation: 13114

The DataProvider is globally shared across the application, so you can't assign more than one.

But you can easily implement a custom data provider that wraps some other data providers and calls their InsertEvent/ReplaceEvent methods sequentially. For example:

public class MultiDataProvider : AuditDataProvider
{
    private AuditDataProvider[] _providers;
    public MultiDataProvider(AuditDataProvider[] providers)
    {
        _providers = providers;
    }
    public override object InsertEvent(AuditEvent auditEvent)
    {
        object eventId = null;
        foreach (var dp in _providers)
        {
            eventId = dp.InsertEvent(auditEvent);
        }
        return eventId;
    }
    public async override Task<object> InsertEventAsync(AuditEvent auditEvent)
    {
        object eventId = null;
        foreach (var dp in _providers)
        {
            eventId = await dp.InsertEventAsync(auditEvent);
        }
        return eventId;
    }
    public override void ReplaceEvent(object eventId, AuditEvent auditEvent)
    {
        foreach (var dp in _providers)
        {
            dp.ReplaceEvent(eventId, auditEvent);
        }
    }
    public async override Task ReplaceEventAsync(object eventId, AuditEvent auditEvent)
    {
        foreach (var dp in _providers)
        {
            await dp.ReplaceEventAsync(eventId, auditEvent);
        }
    }

}

Then on your startup code, you just configure your MultiDataProvider as the data provider, for example:

Audit.Core.Configuration.DataProvider = new MultiDataProvider(
    new AuditDataProvider[]
    {
        new ElasticsearchDataProvider(_ => _
             .ConnectionSettings(new Uri(elasticUri))
                .Index("sample-index")
                .Id(ev => Guid.NewGuid())),
        new UdpDataProvider()
        {
            RemoteAddress = IPAddress.Parse("127.0.0.1"),
            RemotePort = 6060
        }
    }
);

Upvotes: 9

Related Questions