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