test: add file logging and rotation tests

This commit is contained in:
Joseph Doherty
2026-02-23 01:05:10 -05:00
parent e31ba04fdb
commit 8878301c7f
2 changed files with 61 additions and 0 deletions

View File

@@ -0,0 +1,60 @@
using Serilog;
namespace NATS.Server.Tests;
public class LoggingTests : IDisposable
{
private readonly string _logDir;
public LoggingTests()
{
_logDir = Path.Combine(Path.GetTempPath(), $"nats-log-test-{Guid.NewGuid():N}");
Directory.CreateDirectory(_logDir);
}
public void Dispose()
{
try { Directory.Delete(_logDir, true); } catch { }
}
[Fact]
public void File_sink_creates_log_file()
{
var logPath = Path.Combine(_logDir, "test.log");
using var logger = new LoggerConfiguration()
.WriteTo.File(logPath)
.CreateLogger();
logger.Information("Hello from test");
logger.Dispose();
File.Exists(logPath).ShouldBeTrue();
var content = File.ReadAllText(logPath);
content.ShouldContain("Hello from test");
}
[Fact]
public void File_sink_rotates_on_size_limit()
{
var logPath = Path.Combine(_logDir, "rotate.log");
using var logger = new LoggerConfiguration()
.WriteTo.File(
logPath,
fileSizeLimitBytes: 200,
rollOnFileSizeLimit: true,
retainedFileCountLimit: 3)
.CreateLogger();
// Write enough to trigger rotation
for (int i = 0; i < 50; i++)
logger.Information("Log message number {Number} with some padding text", i);
logger.Dispose();
// Should have created rotated files
var logFiles = Directory.GetFiles(_logDir, "rotate*.log");
logFiles.Length.ShouldBeGreaterThan(1);
}
}

View File

@@ -13,6 +13,7 @@
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" />
<PackageReference Include="NATS.NKeys" />
<PackageReference Include="Serilog.Sinks.File" />
</ItemGroup>
<ItemGroup>