NLog与VS 2008单元测试

5

我正在试图在日志文件中记录一些条目(Log.Trace / Log.Debug),同时运行VS单元测试。我还通过类的DeploymentItem属性将文件NLog.config复制到输出目录。但是我的日志文件没有被创建。请问如何像我们为普通Web应用程序做的那样记录条目到文件中。

2个回答

12

我刚找到了这个问题的解决方案:

在你的单元测试项目中添加App.config文件,其内容如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
  </configSections>

  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <targets>
      <target name="debugLog" xsi:type="Console" />
    </targets>

    <rules>
      <logger name="*" minlevel="Debug" writeTo="debugLog"></logger>
    </rules>

  </nlog>

</configuration>

您可以像使用NLog.config文件一样放置任何配置。


0

不幸的是,那是目前唯一的XML解决方案。这不仅仅与单元测试有关。NLog.config不能与任何控制台应用程序一起使用。

不知道这是设计上的问题还是疏忽。无论如何,我不认为将NLog.config移动到App.config部分是令人满意的方式 =/

也许值得注意的是,有可能直接从代码中配置nlog,在某些情况下可能会有所帮助。 人们也可以很高兴地发现nlog调试选项,它将记录处理配置文件、注册目标等整个过程...

要打开它,只需向nlog元素添加internalLogFile和internalLogLevel属性:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" internalLogFile="C:/logs/nlog.txt" internalLogLevel="Debug">

或者从代码中:

    InternalLogger.LogFile = @"c:\logs\nlog.txt";

    InternalLogger.LogLevel = LogLevel.Trace;

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