test: add file logging and rotation tests
This commit is contained in:
60
tests/NATS.Server.Tests/LoggingTests.cs
Normal file
60
tests/NATS.Server.Tests/LoggingTests.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@
|
||||
<PackageReference Include="xunit" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" />
|
||||
<PackageReference Include="NATS.NKeys" />
|
||||
<PackageReference Include="Serilog.Sinks.File" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
Reference in New Issue
Block a user