From e1e3796192c3e98dbd4d0154013f2f8666b30313 Mon Sep 17 00:00:00 2001 From: Thomas Ardal Date: Wed, 3 Jul 2024 10:19:37 +0200 Subject: [PATCH] Migrate OnFilter to use OnMessageFilter event on Elmah.Io.Client --- .../Sinks/ElmahIo/ElmahIOSink.cs | 14 +++++++---- .../Sinks/ElmahIo/ElmahIOSinkTest.cs | 23 +++++++++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/src/Serilog.Sinks.ElmahIo/Sinks/ElmahIo/ElmahIOSink.cs b/src/Serilog.Sinks.ElmahIo/Sinks/ElmahIo/ElmahIOSink.cs index 7968b05..f60bc42 100644 --- a/src/Serilog.Sinks.ElmahIo/Sinks/ElmahIo/ElmahIOSink.cs +++ b/src/Serilog.Sinks.ElmahIo/Sinks/ElmahIo/ElmahIOSink.cs @@ -69,6 +69,15 @@ public async Task EmitBatchAsync(IEnumerable batch) Timeout = new TimeSpan(0, 0, 30), UserAgent = UserAgent(), }); + + api.Messages.OnMessageFilter += (sender, args) => + { + var filter = _options.OnFilter?.Invoke(args.Message); + if (filter.HasValue && filter.Value) + { + args.Filter = true; + } + }; api.Messages.OnMessage += (sender, args) => { _options.OnMessage?.Invoke(args.Message); @@ -109,11 +118,6 @@ public async Task EmitBatchAsync(IEnumerable batch) QueryString = QueryString(logEvent), }; - if (_options.OnFilter != null && _options.OnFilter(message)) - { - continue; - } - messages.Add(message); } diff --git a/test/Serilog.Sinks.ElmahIo.Tests/Sinks/ElmahIo/ElmahIOSinkTest.cs b/test/Serilog.Sinks.ElmahIo.Tests/Sinks/ElmahIo/ElmahIOSinkTest.cs index 9e9001c..d44188f 100644 --- a/test/Serilog.Sinks.ElmahIo.Tests/Sinks/ElmahIo/ElmahIOSinkTest.cs +++ b/test/Serilog.Sinks.ElmahIo.Tests/Sinks/ElmahIo/ElmahIOSinkTest.cs @@ -192,6 +192,29 @@ await sink.EmitBatchAsync(new List Assert.That(loggedMessage.Category, Is.EqualTo("category")); } + [Test] + public async Task CanFilterBatchFromOptions() + { + // Arrange + var messages = 0; + var options = new ElmahIoSinkOptions("API_KEY", Guid.NewGuid()) + { + OnFilter = msg => true, + OnMessage = msg => messages++ + }; + var sink = new ElmahIoSink(options); + + // Act + await sink.EmitBatchAsync(new List + { + new(Now, LogEventLevel.Error, null, new MessageTemplate("Test1", new List()), new List()) + }); + + // Assert + Assert.That(messages, Is.EqualTo(0)); + + } + private static Exception Exception() { return new Exception("error", new DivideByZeroException());