除非强行处理,否则仅显示第一次日志记录 [英] Only first logging shows unless forcefully disposing
问题描述
我正在使用 vs 2017,编写一个 netcoreapp2.0 库,并使用 UnitTest 项目对其进行测试(XUnit 和 NUnit 给出相同的结果).
我注意到除非我强行处理我的 Serilog 记录器,否则只有第一行会以 Seq 结尾.
I'm using vs 2017, writing a netcoreapp2.0 library, and testing it with a UnitTest project (XUnit and NUnit give same results).
I've noticed that unless I'm forcefully Disposing of my Serilog logger, only the first line will end up in Seq.
这是我的 2 节课.图书馆一:
Here are my 2 classes. The library one:
public class Class1
{
public static Logger _log;
public Class1(Logger log)
{
_log = log;
_log.Verbose("Class 1 constructor fineshed");
}
public void LogMessage(string s)
{
_log.Debug("Got message: {Message}", s);
}
}
和单元测试:
public class UnitTest1
{
public static Logger _log = new LoggerConfiguration()
.WriteTo.Seq("http://localhost:5341", Serilog.Events.LogEventLevel.Verbose)
.MinimumLevel.Verbose()
.CreateLogger();
[Fact]
public void Test1()
{
_log.Debug("Test 1 logging");
var c = new Class1(_log);
c.LogMessage("Logging from test");
_log.Information("Test fineshed");
_log.Dispose(); // Without this, only "Test 1 logging" is logged.
}
}
引用的程序集(来自单元测试项目):
Referenced assemblies (from unit test project):
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0-preview-20170628-02" />
<PackageReference Include="serilog" Version="2.5.0" />
<PackageReference Include="serilog.sinks.seq" Version="3.3.3" />
<PackageReference Include="xunit" Version="2.2.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
有什么建议吗?
(这是一个演示项目的链接,打开 vs 2017 恢复包并运行测试:演示项目 )
(here's a link to a demo project, open with vs 2017 restore the packages and run the test : demo project )
推荐答案
根据 Stephen 的建议,问题是记录器的生命范围.
As per Stephen suggestions, the problem was the life scope of the logger.
由于我是从单元测试类进行日志记录,我觉得处理记录器是错误的,但解决方案是从使用类变量记录器更改为使用静态全局记录器.
这允许我在测试创建时设置一次,并在所有测试运行后处理一次:
Since I'm logging from a unit test class, I feel like disposing of the logger was wrong, but the solution was to change from using a class variable logger to using the static global logger.
That allows me to set it up once on test creation, and dispose of it once after all tests run :
[SetUpFixture]
public class TestsSetup
{
[OneTimeSetUp]
public void RunBeforeAnyTests()
{
Log.Logger = new LoggerConfiguration().Enrich.WithExceptionDetails()
.WriteTo.Seq("http://localhost:5341")
.MinimumLevel.Verbose()
.CreateLogger();
}
[OneTimeTearDown]
public void RunAfterAnyTests()
{
Log.CloseAndFlush();
}
}
我遇到的主要困惑是 CloseAndFlush
存在于静态代码中,但不存在于使用
The main confusion I had was that the CloseAndFlush
exists on the static one, but not on the ILogger
you get when creating one with
Logger _log = new LoggerConfiguration()....
这就是为什么我无法关闭并刷新我的变量 1.
hence why i wasn't able to close and flush my variable one.
这篇关于除非强行处理,否则仅显示第一次日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!