Skip to content

Commit be88611

Browse files
committed
Don't write a spurious SelfLog event when disposing an unused sink in durable mode
1 parent b4136b3 commit be88611

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed

src/Serilog.Sinks.Seq/Sinks/Seq/Durable/BookmarkFile.cs

+6
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,12 @@ sealed class BookmarkFile : IDisposable
2424

2525
public BookmarkFile(string bookmarkFilename)
2626
{
27+
var directory = Path.GetDirectoryName(bookmarkFilename);
28+
if (!string.IsNullOrWhiteSpace(directory) && !Directory.Exists(directory))
29+
{
30+
Directory.CreateDirectory(directory);
31+
}
32+
2733
_bookmark = System.IO.File.Open(bookmarkFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
2834
}
2935

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
using System;
2+
using System.IO;
3+
using System.Net;
4+
using System.Threading;
5+
using System.Threading.Tasks;
6+
using Serilog.Sinks.Seq.Durable;
7+
using Serilog.Sinks.Seq.Http;
8+
using Serilog.Sinks.Seq.Tests.Support;
9+
using Xunit;
10+
11+
namespace Serilog.Sinks.Seq.Tests.Durable;
12+
13+
public class DurableSeqSinkTests
14+
{
15+
[Fact]
16+
public void SinkCanBeDisposedCleanlyWhenUnused()
17+
{
18+
var path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("n"), "buffer");
19+
var sink = new DurableSeqSink(
20+
new TestIngestionApi(_ => Task.FromResult(new IngestionResult(true, HttpStatusCode.Accepted, null))),
21+
new SeqCompactJsonFormatter(),
22+
path,
23+
100,
24+
TimeSpan.FromSeconds(1),
25+
null,
26+
null,
27+
new ControlledLevelSwitch(),
28+
null);
29+
30+
// No events written, so files/paths should not exist;
31+
Assert.False(Directory.Exists(path));
32+
33+
using var collector = new SelfLogCollector();
34+
sink.Dispose();
35+
Assert.Empty(collector.Messages);
36+
}
37+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Threading;
4+
using Serilog.Debugging;
5+
6+
namespace Serilog.Sinks.Seq.Tests.Support;
7+
8+
sealed class SelfLogCollector: IDisposable
9+
{
10+
static readonly AsyncLocal<SelfLogCollector?> Collectors = new();
11+
12+
static SelfLogCollector()
13+
{
14+
SelfLog.Enable(m => Collectors.Value?.Messages.Add(m));
15+
}
16+
17+
public SelfLogCollector()
18+
{
19+
if (Collectors.Value != null)
20+
throw new InvalidOperationException("SelfLogCollector is already in use in this task.");
21+
22+
Collectors.Value = this;
23+
}
24+
25+
public IList<string> Messages { get; } = new List<string>();
26+
27+
public void Dispose()
28+
{
29+
Collectors.Value = null;
30+
}
31+
}

0 commit comments

Comments
 (0)