Use try-catch when adding or removing logEntry (#848)

* Use try-catch when removing logEntry

* .

* try catch add

* Add extra check

* ...
This commit is contained in:
Stef Heyenrath
2022-11-21 07:30:27 +01:00
committed by GitHub
parent ef5f988786
commit 38634ac65a
2 changed files with 54 additions and 7 deletions

View File

@@ -269,29 +269,55 @@ namespace WireMock.Owin
{
_options.Logger.DebugRequestResponse(_logEntryMapper.Map(entry), entry.RequestMessage.Path.StartsWith("/__admin/"));
if (addRequest)
// If addRequest is set to true and MaxRequestLogCount is null or does have a value greater than 0, try to add a new request log.
if (addRequest && _options.MaxRequestLogCount is null or > 0)
{
_options.LogEntries.Add(entry);
TryAddLogEntry(entry);
}
if (_options.MaxRequestLogCount != null)
// In case MaxRequestLogCount has a value greater than 0, try to delete existing request logs based on the count.
if (_options.MaxRequestLogCount is > 0)
{
var logEntries = _options.LogEntries.ToList();
foreach (var logEntry in logEntries.OrderBy(le => le.RequestMessage.DateTime).Take(logEntries.Count - _options.MaxRequestLogCount.Value))
{
_options.LogEntries.Remove(logEntry);
TryRemoveLogEntry(logEntry);
}
}
if (_options.RequestLogExpirationDuration != null)
// In case RequestLogExpirationDuration has a value greater than 0, try to delete existing request logs based on the date.
if (_options.RequestLogExpirationDuration is > 0)
{
var checkTime = DateTime.UtcNow.AddHours(-_options.RequestLogExpirationDuration.Value);
foreach (var logEntry in _options.LogEntries.ToList().Where(le => le.RequestMessage.DateTime < checkTime))
{
_options.LogEntries.Remove(logEntry);
TryRemoveLogEntry(logEntry);
}
}
}
private void TryAddLogEntry(LogEntry logEntry)
{
try
{
_options.LogEntries.Add(logEntry);
}
catch
{
// Ignore exception (can happen during stress testing)
}
}
private void TryRemoveLogEntry(LogEntry logEntry)
{
try
{
_options.LogEntries.Remove(logEntry);
}
catch
{
// Ignore exception (can happen during stress testing)
}
}
}
}

View File

@@ -5,6 +5,7 @@ using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Moq;
using Newtonsoft.Json;
using NFluent;
@@ -374,6 +375,26 @@ public class WireMockServerAdminTests
server.Stop();
}
[Fact]
public async Task WireMockServer_Admin_Logging_SetMaxRequestLogCount_To_0_Should_Not_AddLogging()
{
// Assign
var client = new HttpClient();
// Act
var server = WireMockServer.Start();
server.SetMaxRequestLogCount(0);
await client.GetAsync("http://localhost:" + server.Port + "/foo1").ConfigureAwait(false);
await client.GetAsync("http://localhost:" + server.Port + "/foo2").ConfigureAwait(false);
await client.GetAsync("http://localhost:" + server.Port + "/foo3").ConfigureAwait(false);
// Assert
server.LogEntries.Should().BeEmpty();
server.Stop();
}
[Fact]
public void WireMockServer_Admin_WatchStaticMappings()
{