为传统 .net framework 项目切换 nlog 日志

1、安装 nuget 包:NLog、NLog.Targets.Trace

2、在 web.config 中 configSections 下添加 nlog 配置

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

3、添加 nlog 配置,替换原有 listener

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- 添加 NLog 配置节 -->
    <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">
    <extensions>
      <add assembly="NLog.Targets.Trace" />
    </extensions>
    <targets>
      <!-- 生产环境可使用 ${basedir} 替换路径 -->
      <target xsi:type="File" name="fileTarget" 
              fileName="D:\LogFiles\${shortdate}.log" 
              layout="${longdate} [${level:uppercase=true}] ${logger:shortName=true} - ${message} ${exception:format=tostring}" 
              archiveFileName="D:\LogFiles\${shortdate}-archived-{#}.log" 
              archiveAboveSize="10485760" 
              archiveEvery="Day" 
              archiveNumbering="Rolling" 
              maxArchiveFiles="365" />
      <target xsi:type="Console" name="consoleTarget" 
              layout="${time} [${level:uppercase=true}] ${message}" />
    </targets>
    <rules>
      <!-- 记录级别:Fatal、Error、Warn、Info、Debug、Trace -->
      <logger name="*" minlevel="Info" writeTo="fileTarget" />
      <logger name="*" minlevel="Debug" writeTo="consoleTarget" />
    </rules>
  </nlog>
  <system.diagnostics>
    <sources>
      <source name="Test.Module" switchValue="All">
        <listeners>
          <clear />
          <!-- 使用 NLog 日志 -->
          <add name="nlog" />
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="nlog" type="NLog.NLogTraceListener, NLog.Targets.Trace" />
    </sharedListeners>
    <!-- 为 NLog 性能优化,关闭两个配置 -->
    <trace autoflush="false" useGlobalLock="false">
      <!-- NLog 监听器在代码中初始化-->
    </trace>
  </system.diagnostics>
</configuration>

4、此时理论上原有的 Trace 日志就都由 NLog 进行记录了。

5、使用 NLog 直接记录方法:

namespace Test
{
    public class TestHelper
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        
        public void DoSomething(string input)
        {
            Logger.Info("输入:" + input);
        }
    }
}

参考链接:

https://github.com/NLog/NLog/wiki/Configuration-file#nlog-config-xml

https://github.com/NLog/NLog/wiki/NLog-Trace-Listener-for-System-Diagnostics-Trace

posted @ 2025-08-12 17:17  不是豆豆  阅读(13)  评论(0)    收藏  举报
友情链接:迷途