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

北城余情 提交于 2020-08-09 14:09:17

问题


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));

回答1:


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
        }
    }
);


来源:https://stackoverflow.com/questions/58203562/in-audit-net-is-there-a-way-to-use-multiple-output-provider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!