How to log with Nlog in SpecFlow?

Art*_*yom 5 c# nlog xunit specflow

SpecFlow writes its output into Console like this:

Given the "TestOperator" user is logged in
-> done: WebUserSteps.GivenTheUserIsLoggedIn("TestOperator", "") (9.5s)
Run Code Online (Sandbox Code Playgroud)

How can we make it use NLog to configure where it should write?

With this:

public class CustomListener : ITraceListener
{
    private Logger Log = LogManager.GetLogger("SPECFLOW");

    public void WriteTestOutput(string message)
    {
        Log.Trace(message);
    }

    public void WriteToolOutput(string message)
    {
        Log.Trace(message);
    }
}
Run Code Online (Sandbox Code Playgroud)

And

[Binding]
public class ScenarioContextInitializer 
{
    private readonly IObjectContainer _container;

    public ScenarioContextInitializer(ScenarioContext scenarioContext)
    {
        _container = (scenarioContext ?? throw new ArgumentNullException(nameof(scenarioContext))).ScenarioContainer;
    }

    [Before]
    protected void Load()
    {
        _container.RegisterTypeAs<CustomListener, ITraceListener>();
    }
}
Run Code Online (Sandbox Code Playgroud)

It didn't work. I know there is ability to add plugins but that seems too much overhead.

Also we use ObjectivityLtd Test.Automation extensions.

It works via xunit tests generated by SpecFlow.xUnit

Jul*_*ian 0

问题可能是 NLog 找不到它的配置。

运行单元测试时,会移动 dll 而不是 nlog.config

有多种解决方案:

从固定路径加载配置,例如

LogManager.Configuration = new XmlLoggingConfiguration("c:/mydir/nlog.config");
Run Code Online (Sandbox Code Playgroud)

或者从代码而不是配置进行设置,例如:

var config = new LoggingConfiguration();
config.AddRuleForAllLevels(new FileTarget()
{
    FileName = "c:/temp/logfile.log"
});
LogManager.Configuration = config; //apply config
Run Code Online (Sandbox Code Playgroud)

参见维基百科

如果问题仍然存在,请检查内部日志