Skip to content

Commit b73decb

Browse files
authored
Merge pull request #44 from Blaisor/async
Added support for TryReadAsync() with CancellationToken
2 parents 30acd9f + 4b1170e commit b73decb

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

src/Serilog.Formatting.Compact.Reader/LogEventReader.cs

+21
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,27 @@ public bool TryRead([NotNullWhen(true)] out LogEvent? evt)
102102
return ParseLine(line);
103103
}
104104

105+
#if FEATURE_READ_LINE_ASYNC_CANCELLATION
106+
/// <inheritdoc cref="TryReadAsync()" />
107+
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
108+
public async Task<LogEvent?> TryReadAsync(CancellationToken cancellationToken)
109+
{
110+
var line = await _text.ReadLineAsync(cancellationToken).ConfigureAwait(false);
111+
_lineNumber++;
112+
while (string.IsNullOrWhiteSpace(line))
113+
{
114+
if (line == null)
115+
{
116+
return null;
117+
}
118+
line = await _text.ReadLineAsync(cancellationToken).ConfigureAwait(false);
119+
_lineNumber++;
120+
}
121+
122+
return ParseLine(line);
123+
}
124+
#endif
125+
105126
/// <summary>
106127
/// Read a single log event from a JSON-encoded document.
107128
/// </summary>

src/Serilog.Formatting.Compact.Reader/Serilog.Formatting.Compact.Reader.csproj

+4
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@
2828
<ImplicitUsings>enable</ImplicitUsings>
2929
</PropertyGroup>
3030

31+
<PropertyGroup Condition=" '$(TargetFramework)' == 'net8.0' ">
32+
<DefineConstants>$(DefineConstants);FEATURE_READ_LINE_ASYNC_CANCELLATION</DefineConstants>
33+
</PropertyGroup>
34+
3135
<ItemGroup>
3236
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
3337
<PackageReference Include="Serilog" Version="4.0.0" />

test/Serilog.Formatting.Compact.Reader.Tests/LogEventReaderTests.cs

+6
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System;
55
using System.Collections.Generic;
66
using System.IO;
7+
using System.Threading;
78
using System.Threading.Tasks;
89
using Xunit;
910

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

161+
#if NET7_0_OR_GREATER
162+
using var asyncReader2 = new LogEventReader(new StringReader(document));
163+
await Assert.ThrowsAsync<InvalidDataException>(async () => await asyncReader2.TryReadAsync(CancellationToken.None));
164+
#endif
165+
160166
Assert.Throws<InvalidDataException>(() => LogEventReader.ReadFromString(document));
161167
}
162168
}

0 commit comments

Comments
 (0)