如何在nlog.config中设置debugEnabled / InfoEnabled

时间:2018-02-28 11:23:09

标签: c# configuration nlog

我有NLog包的Logger, 我想在配置记录器文件中定义trace enable = true。

我该怎么做?

我的NLog.config文件:

   <?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <targets>
    <target name="logfile" xsi:type="File" fileName="file.txt" />
    <target name="logconsole" xsi:type="Console" />
  </targets>

  <rules>
    <logger name="*" maxlevel="Trace" minlevel="Trace" writeTo="logfile" />

  </rules>
</nlog>

2 个答案:

答案 0 :(得分:2)

您可以通过在NLog.config的minLevel部分设置rules属性来执行此操作;

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

Debug会写出DebugInfoWarnErrorFatal级日志消息。仅跳过Trace

修改

相反,如果您只想记录Trace,那么设置maxLevel就像这样;

<rules>
  <logger name="*" maxlevel="Trace" writeTo="CSVFile" />
</rules>

要仅记录特定的中间级别,请同时使用minLevelmaxLevel;

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

<强> EDIT2

我调整了你的配置文件,使得输出记录到控制台而不是文件;

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <targets>
    <target name="logfile" xsi:type="File" fileName="file.txt" />
    <target name="logconsole" xsi:type="Console" />
  </targets>

  <rules>
    <logger name="*" maxlevel="Trace" writeTo="logconsole" />
  </rules>
</nlog>

当我在测试应用程序中运行时,我正在编写多个日志级别,如此;

_logger.Trace("trace text");
_logger.Debug("debug text");
_logger.Info("info text");
_logger.Warn("warn text");
_logger.Error("error text");
_logger.Fatal("fatal text");

只有Trace文本显示在控制台窗口中。但需要注意的是,配置文件中的XML必须正确格式化。上面的示例正如我的测试应用程序中所述。

答案 1 :(得分:2)

您可以通过创建多个记录器实例来创建多个级别的日志记录,例如

 <rules>
  <!-- add your logging rules here -->
  <!-- different logger instances for different environments, no levels are mentioned explicitly, can be done if exclusion of some levels is required -->
  <logger name="Log.Dev" minlevel="Debug" writeTo="database" enabled="true" />
  <logger name="Log.Staging" minlevel="Info" writeTo="database" enabled="true" />
  <logger name="Log.Production" minlevel="Error" writeTo="database" enabled="true" />
</rules>

在初始化之后,给出要初始化的记录器的名称

        /// <summary>
    /// The log. 
    /// Getting Logger instance from key name defined in Web.config of main web file. Key name is LoggerInstanceName
    /// On the basis of name , logger instance and defined rules can be switched from one to another.
    /// </summary>
    private static readonly NLog.Logger Log = LogManager.GetLogger(Convert.ToString(ConfigurationManager.AppSettings.Get("LoggerInstance")));

另外,请不要忘记在应用设置中添加密钥

<appSettings>
<!--logger instance name-->
<add key="LoggerInstanceName" value="Log.Dev" />
</appSettings>