如何在运行时更改NLog布局?

时间:2018-03-17 13:59:50

标签: c# logging nlog

我创建了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"
      throwExceptions="false"
      throwConfigExceptions="true"> <!--make NLog complain, when something is wrong with the configuration-->


  <targets>
    <target name="logfile" xsi:type="File" 
            fileName="${basedir}/Logs/Log_${shortdate}.txt" 
            layout="[${longdate}] [${uppercase:${level}}] ${message} ${exception:format=tostring}"
            />
    <target name="logconsole" xsi:type="ColoredConsole" 
            layout="[${longdate}] ${uppercase:${level}}: ${message} ${exception:format=tostring}"
            />    
  </targets>

  <rules>
    <logger name="*" minlevel="Info" writeTo="logconsole" />
    <logger name="*" minlevel="Debug" writeTo="logfile" />

  </rules>
</nlog>

当我呼叫logger.Info("Hello World");时,我在控制台和文件中都得到了输出:

[2018-03-17 15:34:24.2843] INFO: Hello World

哪个好。 现在在某些情况下我不想显示日期时间部分,我只想在控制台中显示它。

我如何使用NLog做到这一点?

我想要的解决方案是:

logger.Info("Hello World", writeTo: "logconsole", layout: "[${uppercase:${level}}] ${message}");

我尝试添加新的taget

<target name="logconsole_simple" xsi:type="ColoredConsole"
            layout="${uppercase:${level}}: ${message} ${exception:format=tostring}"/>

和新规则:

<logger name="logconsole_simple"  level="Info" writeTo="logconsole_simple" />

并称之为:

logger.Log(LogEventInfo.Create(LogLevel.Info, "logconsole_simple", "simple message!"));

但它仍然显示日期时间部分并将其记录到文件中(我不想要)。 如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

为您的特殊情况添加目标和规则,并按名称引用您的记录器。

配置:

<?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"
      throwExceptions="false"
      throwConfigExceptions="true"><!--make NLog complain, when something is wrong with the configuration-->

  <targets>
    <target name="logfile" xsi:type="File"
            fileName="${basedir}/Logs/Log_${shortdate}.txt"
            layout="[${longdate}] [${uppercase:${level}}] ${message} ${exception:format=tostring}"
    />
    <target name="logconsole_default" xsi:type="Console"
            layout="[${longdate}] ${uppercase:${level}}: ${message} ${exception:format=tostring}"
    />
    <target name="logconsole_other" xsi:type="Console"
            layout="${uppercase:${level}}: ${message} ${exception:format=tostring}"
    />
  </targets>

  <rules>
    <logger name="default" minlevel="Debug" writeTo="logfile" />
    <logger name="default" minlevel="Info" writeTo="logconsole_default" />
    <logger name="other" minlevel="Info" writeTo="logconsole_other" />
  </rules>
</nlog>

用法:

internal class Program
{
    private static readonly Logger DefaultLogger = LogManager.GetLogger("default");

    private static readonly Logger OtherLogger = LogManager.GetLogger("other");

    private static void Main(string[] args)
    {
        for (var i = 0; i < 2; i++)
        {
            if (i % 2 == 0)
            {
                DefaultLogger.Info("normal log message");
            }
            else
            {
                OtherLogger.Info("special case");
            }
        }
    }
}

编辑:如果你真的想通过修改你现有的目标和规则在代码中做到这一点,你可以(这将使用原始帖子中的配置):

using System.Linq;
using NLog;
using NLog.Layouts;
using NLog.Targets;

internal class Program
{
    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

    private static void Main(string[] args)
    {
        for (var i = 0; i < 2; i++)
        {                
            if (i % 2 == 0)
            {
                Logger.Info("normal log message");
            }
            else
            {
                // reconfigure
                var consoleTarget = LogManager.Configuration.FindTargetByName<ColoredConsoleTarget>("logconsole");
                var oldLayout = consoleTarget.Layout;
                consoleTarget.Layout = new SimpleLayout { Text = "${uppercase:${level}}: ${message} ${exception:format=tostring}" };
                var fileRule = LogManager.Configuration.LoggingRules.Single(r => r.Targets.Any(t => t.Name == "logfile"));
                LogManager.Configuration.LoggingRules.Remove(fileRule);
                LogManager.Configuration.Reload();

                Logger.Info("special case");

                // replace originals
                consoleTarget.Layout = oldLayout;
                LogManager.Configuration.LoggingRules.Add(fileRule);
                LogManager.Configuration.Reload();
            }
        }
    }
}