如何解决NLog记日志性能慢的问题

最近写了一个模拟器程序,由于模拟器中要在日志中记录对象实时变化时的完整状态,导致日志数量猛增,跑了一分钟程序就有3000多条日志。

日志多没关系,但是我发现在增加日志内容后程序在很多运行周期中常常超时。难道这个.Net Core程序用的NLog还要占用主线程的CPU资源去记录日志吗?仔细研读了NLog的文档后,发现NLog在默认状态下确实是使用记录日志时所用的线程来保存日志的。

但是你可以打开异步开关来实现在日志自己的线程中保存日志,具体做法是在配置文件的 targets 增加 async = “true” 属性。下面是示例配置:

<?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"
      internalLogLevel="Info"
      internalLogFile="${basedir}/logs/internal-nlog.txt">

  <!-- 在这里把 async="true" 就可以实现异步保存日志了 -->
  <targets async="true">
    <!-- write logs to file  -->
    <target xsi:type="File" name="allfile" fileName="${basedir}/logs/nlog-all-${shortdate}.log"
            keepFileOpen="true"
            archiveFileName="${basedir}/logs/archives/nlog-all-${longdate}.log"
            archiveAboveSize="4096000"
            archiveEvery="Day"
            maxArchiveFiles="35"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

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

  <!-- rules to map from logger name to target -->
  <rules>
    <logger name="*" minlevel="Info" writeTo="logconsole" />
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Info" writeTo="allfile" />
    <!--Skip non-critical Microsoft logs and so log only own logs-->
    <!--logger name="Microsoft.*" maxlevel="Info" final="true" /-->
  </rules>
</nlog>

实际运行以后,即使是在压力极大的情况下也没有再出现过运行周期超时的问题,成功地解决了写日志耗时过高的问题。

由于是异步写日志,NLog默认设置了一个缓存值,这个值默认是10000条日志,如果 10000 条以上了待写入的时候又来了其他日志,NLog 会直接忽略。当然你可以选择扩大缓存,或者让发起记日志的线程等待缓存被清空。

最后,记得在程序运行结束时执行以下语句,这样才能保证日志被完整保存。

// Flush logs
NLog.LogManager.Shutdown();

参考资料:
https://github.com/NLog/NLog/wiki/AsyncWrapper-target

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
首先,需要安装NLog NuGet包。可以在Visual Studio中右键点击项目,在“管理NuGet程序包”中搜索并安装NLog。 然后,在应用程序中添加一个NLog配置文件,命名为“NLog.config”。在该配置文件中,可以指定日志录器的行为,例如指定日志输出到控制台还是文件中。 下面是一个简单的NLog配置文件示例: ```xml <?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" internalLogLevel="Info" internalLogFile="c:\temp\nlog-internal.log"> <targets> <target name="console" xsi:type="Console" /> <target name="file" xsi:type="File" fileName="c:\temp\log.txt" /> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="console" /> <logger name="*" minlevel="Debug" writeTo="file" /> </rules> </nlog> ``` 接下来,在应用程序中添加一个静态Logger类,该类可以在应用程序中的任何位置使用,以日志消息。以下是Logger类的示例代码: ```csharp using NLog; public static class Logger { private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); public static void Trace(string message) { _logger.Trace(message); } public static void Debug(string message) { _logger.Debug(message); } public static void Info(string message) { _logger.Info(message); } public static void Warn(string message) { _logger.Warn(message); } public static void Error(string message) { _logger.Error(message); } public static void Fatal(string message) { _logger.Fatal(message); } } ``` 最后,在应用程序中使用Logger类日志消息。以下是一个示例: ```csharp public class MyApp { public void Run() { Logger.Info("Application started."); // Do some work here... Logger.Info("Application finished."); } } ``` 这将录两个日志消息,一个在应用程序开始时,一个在应用程序结束时。这些日志消息将根据NLog配置文件中指定的规则,写入控制台和文件。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

surfirst

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值