I have recently started using NLog and I would like to display the log in my application before it is saved into a file.
How can I get the following?
string message = logger.getLog() <---- This is what I need
I have recently started using NLog and I would like to display the log in my application before it is saved into a file.
How can I get the following?
string message = logger.getLog() <---- This is what I need
In this case it's the best (IMO) to use the memory target. (docs memory target)
config:
<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>
log message:
LogManager.GetLogger("logger1").Info("my log message");
retrieval: (see also: 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()
You need to add a proper Target for Nlog to call.
For example MethodCall target
https://github.com/NLog/NLog/wiki/MethodCall-target
Nlog also provide your some helper Target for Web and WinForm if what's what you need. https://www.nuget.org/packages/NLog.Web/
You could write a wrapper around the NLog logger. So you call DavidsLogger.Log(error) and that method stores the log message in memory where you can access it, then calls the usual method on NLog to store the message permanently in the log.
You can create targets
and rules
in Nlog.Config like below:
<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>
This will write the log to console and file. You can also send the log to email. This link can give you a basic understanding of NLog here:
https://www.c-sharpcorner.com/article/basic-understanding-of-nlog/
and here: https://github.com/nlog/NLog/wiki/Configuration-file
Following are the "priority" of levels (copied from above link):
Level Example
You can use my NLogViewer
(https://github.com/dojo90/NLogViewer). It is a wpf
control. I know you wrote win forms
, but maybe you can need it in future.
There is also a nuget package available -> https://www.nuget.org/packages/Sentinel.NLogViewer