如何在不重新启动应用程序的情况下激活运行时日志记录?

How to activate logging in runtime without restarting application?

是否可以在不重启 .NET 应用程序的情况下激活 Serilog 或 NLog 中的日志记录?

我想在应用程序在客户系统上 运行 时激活日志记录以查看问题所在。

NLog 的主要功能之一是您可以在 运行 应用程序时更改配置。

如果你有 nlog.config,你可以启用自动重新加载:

<nlog autoReload="true">
   ...
</nlog>

当您保存对文件的更改时,配置将被重新加载。

例子

例如:

在配置中,您可以更改 globalThreshold<rules> 而 运行。

<?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"
      autoReload="true"
      globalThreshold="Debug" >

  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file  -->
    <target xsi:type="File" name="file1" fileName="c:\temp\nlog-all-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <logger name="*" minlevel="Trace" writeTo="file1" />
  </rules>

</nlog>

来自代码

您也可以从代码更改配置,然后检查 LogManager.Configuration。请注意,如果您还没有配置(来自代码或 nlog.config),则此 属性 为 null