Skip to content

Added support for TryReadAsync() with CancellationToken #44

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/Serilog.Formatting.Compact.Reader/LogEventReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,27 @@ public bool TryRead([NotNullWhen(true)] out LogEvent? evt)
return ParseLine(line);
}

#if FEATURE_READ_LINE_ASYNC_CANCELLATION
/// <inheritdoc cref="TryReadAsync()" />
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
public async Task<LogEvent?> TryReadAsync(CancellationToken cancellationToken)
{
var line = await _text.ReadLineAsync(cancellationToken).ConfigureAwait(false);
_lineNumber++;
while (string.IsNullOrWhiteSpace(line))
{
if (line == null)
{
return null;
}
line = await _text.ReadLineAsync(cancellationToken).ConfigureAwait(false);
_lineNumber++;
}

return ParseLine(line);
}
#endif

/// <summary>
/// Read a single log event from a JSON-encoded document.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<PropertyGroup Condition=" '$(TargetFramework)' == 'net8.0' ">
<DefineConstants>$(DefineConstants);FEATURE_READ_LINE_ASYNC_CANCELLATION</DefineConstants>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Serilog" Version="4.0.0" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

Expand Down Expand Up @@ -157,6 +158,11 @@ public async Task InvalidDataThrowsInvalidDataException(string document)
using var asyncReader = new LogEventReader(new StringReader(document));
await Assert.ThrowsAsync<InvalidDataException>(asyncReader.TryReadAsync);

#if NET7_0_OR_GREATER
using var asyncReader2 = new LogEventReader(new StringReader(document));
await Assert.ThrowsAsync<InvalidDataException>(async () => await asyncReader2.TryReadAsync(CancellationToken.None));
#endif

Assert.Throws<InvalidDataException>(() => LogEventReader.ReadFromString(document));
}
}