【问题标题】:NLog get log message in c#NLog在c#中获取日志消息
【发布时间】:2020-01-16 19:11:28
【问题描述】:

我最近开始使用 NLog,我想在将日志保存到文件之前在我的应用程序中显示它。

如何获得以下内容?

string message = logger.getLog() <---- This is what I need

【问题讨论】:

  • 它是什么应用程序?控制台,网络?
  • NLog get messages in C#的可能重复
  • Windows 窗体应用程序

标签: c# nlog


【解决方案1】:

在这种情况下,最好 (IMO) 使用内存目标。 (docs memory target)

配置:

<targets>  
    <target name="target1" xsi:type="Memory" layout="${message}"/>  
    <target name="target2" xsi:type="File" fileName="C:\log\NLog.log" layout="${longdate}|${message}"/>  
</targets>  

<rules>  
  <logger name="*" minlevel="Error" writeTo="target1,target2" />  
</rules> 

日志消息:

 LogManager.GetLogger("logger1").Info("my log message");

检索:(另见:MemoryTarget class - API docs

var target = LogManager.Configuration.FindTargetByName<MemoryTarget>("target1");
IList<string> logs = target.Logs; 
// show logs etc.
// delete if not needed any more: target.Logs.Clear()

【讨论】:

  • 请注意,NLog 版本。 4.6 引入属性MaxLogsCount。如果想避免内存不足的情况,这可能很有用。
【解决方案2】:

你需要添加一个合适的 Target 供 Nlog 调用。

例如 MethodCall 目标

https://github.com/NLog/NLog/wiki/MethodCall-target

如果您需要的话,Nlog 还为您提供一些帮助 Target for Web 和 WinForm。 https://www.nuget.org/packages/NLog.Web/

https://www.nuget.org/packages/NLog.Windows.Forms/

【讨论】:

    【解决方案3】:

    您可以为 NLog 记录器编写一个包装器。因此,您调用 DavidsLogger.Log(error),该方法将日志消息存储在您可以访问的内存中,然后调用 NLog 上的常用方法将消息永久存储在日志中。

    【讨论】:

      【解决方案4】:

      您可以在 Nlog.Config 中创建targetsrules,如下所示:

      <targets>  
          <target name="console" xsitype="Console" layout="${longdate}|${message}"/>  
           <target name="file" xsitype="File" fileName="C:\log\NLog.log" layout="${longdate}|${message}"/>  
      </targets>  
      
      <rules>  
        <logger name="*" minlevel="Error" writeTo="console,file" />  
      </rules>  
      

      这会将日志写入控制台和文件。您也可以将日志发送到电子邮件。这个链接可以让你在这里对NLog有一个基本的了解:

      https://www.c-sharpcorner.com/article/basic-understanding-of-nlog/

      这里: https://github.com/nlog/NLog/wiki/Configuration-file

      以下是级别的“优先级”(从上面的链接复制):

      关卡示例

      • 致命的最高级别:重要的东西下降
      • 错误,例如应用程序崩溃/异常。
      • 警告不正确的行为,但应用程序可以继续
      • 信息 正常行为,如发送邮件、用户更新个人资料等。
      • 调试执行的查询、用户认证、会话过期
      • 跟踪开始方法 X、结束方法 X 等

      【讨论】:

        【解决方案5】:

        您可以使用我的NLogViewer (https://github.com/dojo90/NLogViewer)。这是一个wpf 控件。我知道你写了win forms,但也许你将来会需要它。

        还有一个 nuget 包可用 -> https://www.nuget.org/packages/Sentinel.NLogViewer

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-06-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-21
          相关资源
          最近更新 更多