【发布时间】:2020-01-16 19:11:28
【问题描述】:
我最近开始使用 NLog,我想在将日志保存到文件之前在我的应用程序中显示它。
如何获得以下内容?
string message = logger.getLog() <---- This is what I need
【问题讨论】:
-
它是什么应用程序?控制台,网络?
-
Windows 窗体应用程序
我最近开始使用 NLog,我想在将日志保存到文件之前在我的应用程序中显示它。
如何获得以下内容?
string message = logger.getLog() <---- This is what I need
【问题讨论】:
在这种情况下,最好 (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()
【讨论】:
MaxLogsCount。如果想避免内存不足的情况,这可能很有用。
你需要添加一个合适的 Target 供 Nlog 调用。
例如 MethodCall 目标
https://github.com/NLog/NLog/wiki/MethodCall-target
如果您需要的话,Nlog 还为您提供一些帮助 Target for Web 和 WinForm。 https://www.nuget.org/packages/NLog.Web/
【讨论】:
您可以为 NLog 记录器编写一个包装器。因此,您调用 DavidsLogger.Log(error),该方法将日志消息存储在您可以访问的内存中,然后调用 NLog 上的常用方法将消息永久存储在日志中。
【讨论】:
您可以在 Nlog.Config 中创建targets 和rules,如下所示:
<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
以下是级别的“优先级”(从上面的链接复制):
关卡示例
【讨论】:
您可以使用我的NLogViewer (https://github.com/dojo90/NLogViewer)。这是一个wpf 控件。我知道你写了win forms,但也许你将来会需要它。
还有一个 nuget 包可用 -> https://www.nuget.org/packages/Sentinel.NLogViewer
【讨论】: