Skip to content

Commit

Permalink
Migrate OnFilter to use OnMessageFilter event on Elmah.Io.Client
Browse files Browse the repository at this point in the history
  • Loading branch information
ThomasArdal committed Jul 3, 2024
1 parent aacbd32 commit e1e3796
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
14 changes: 9 additions & 5 deletions src/Serilog.Sinks.ElmahIo/Sinks/ElmahIo/ElmahIOSink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,15 @@ public async Task EmitBatchAsync(IEnumerable<LogEvent> 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);
Expand Down Expand Up @@ -109,11 +118,6 @@ public async Task EmitBatchAsync(IEnumerable<LogEvent> batch)
QueryString = QueryString(logEvent),
};

if (_options.OnFilter != null && _options.OnFilter(message))
{
continue;
}

messages.Add(message);
}

Expand Down
23 changes: 23 additions & 0 deletions test/Serilog.Sinks.ElmahIo.Tests/Sinks/ElmahIo/ElmahIOSinkTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,29 @@ await sink.EmitBatchAsync(new List<LogEvent>
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<LogEvent>
{
new(Now, LogEventLevel.Error, null, new MessageTemplate("Test1", new List<MessageTemplateToken>()), new List<LogEventProperty>())
});

// Assert
Assert.That(messages, Is.EqualTo(0));

}

private static Exception Exception()
{
return new Exception("error", new DivideByZeroException());
Expand Down

0 comments on commit e1e3796

Please sign in to comment.