使用NLog和MSTest(.NET Core 2.0)

3
我有一个使用.NET 4.7构建的解决方案,其中包含两个项目:
  • 类库(.NET 4.7.2)
  • 单元测试项目(.NET Framework)
我正在尝试将此解决方案迁移到使用.NET Standard | Core。
我已经成功地将类库转移到了.NET Standard 2.0项目。我还将单元测试项目转移到了.NET Core 2.0 mstest project。一切都可以编译。我可以按预期运行我的测试。然而,NLog没有写入任何日志。
在我使用.NET 4.7版本的解决方案中,当我运行单元测试时,通过NLog实际写入了一个日志文件。然而,在新的.NET Standard | Core实现中,这个日志文件没有被写入。我在我的mstest项目中有以下两个文件:

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>

nlog.config

<?xml version="1.0" encoding="utf-8" ?>
<!-- XSD manual extracted from package NLog.Schema: https://www.nuget.org/packages/NLog.Schema-->
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"  
    xsi:schemaLocation="NLog NLog.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    autoReload="true"
    internalLogFile="c:\temp\console-example-internal.log"
    internalLogLevel="Info" >
  <targets>
    <target name="myLogs" xsi:type="File" deleteOldFileOnStartup="true" fileName="${basedir}/logs/MyLogs.json" createDirs="true" keepFileOpen="true" encoding="utf-8" layout="${message}" />
    <target name="traceLogs" xsi:type="File" deleteOldFileOnStartup="true" fileName="${basedir}/logs/trace.log" createDirs="true" keepFileOpen="true" encoding="utf-8" layout="[${longdate}] ${message}${exception:format=ToString}"></target>
  </targets>

  <rules>
    <logger name="MyLogger" minlevel="Info" writeTo="myLogs" />
    <logger name="TraceLogger" minlevel="Trace" writeTo="traceLogs" />
  </rules>
</nlog>

在我的mstest项目中,我还添加了以下引用:
  • Microsoft.Extensions.DependencyInjection
  • NLog
  • NLog.Extensions.Logging

我按照这里列出的步骤进行操作。但是,我只完成了前两步。对于mstest项目,我需要那些东西吗?如果需要,它们在哪里?这似乎是为了一些已经在运行中的东西而添加了很多额外的内容。

1个回答

5
在运行单元测试时,很难找到nlog.config,因为实现会将DLL(大多数情况下不包括nlog.config)移动到临时文件夹中。
建议在单元测试项目中从代码配置NLog。(如何在此处操作
另一种选择是手动加载NLog配置文件。您需要向XmlLoggingConfiguration构造函数提供nlog.config的路径:
LogManager.Configuration = new XmlLoggingConfiguration(pathToNLogConfig);

题外话但与之相关:

在单元测试中,建议将事件日志写入内存而不是文件中,例如使用内存目标。这使得单元测试更加健壮。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接