As @mafu's answer suggests:
[Create] a custom NLog
[memory] Target
and [link] it to a TextBox
.
This sample will 'link it' via event
and Event Handler delegates.
Define a NLog Memory Target as a Type
public class NlogMemoryTarget : Target
{
public event EventHandler<string> OnLog;
public NlogMemoryTarget(string name, LogLevel level) : this(name, level, level) {}
public NlogMemoryTarget(string name, LogLevel minLevel, LogLevel maxLevel)
{
// important: we want LogManager.Configuration property assign behaviors \ magic to occur
// see: https://stackoverflow.com/a/3603571/1366179
var config = LogManager.Configuration;
// Add Target and Rule to their respective collections
config.AddTarget(name, this);
config.LoggingRules.Add(new LoggingRule("*", minLevel, maxLevel, this));
LogManager.Configuration = config;
}
[Obsolete]
protected override void Write(AsyncLogEventInfo[] logEvents)
{
foreach (var logEvent in logEvents) {
Write(logEvent.LogEvent);
}
}
protected override void Write(AsyncLogEventInfo logEvent)
{
Write(logEvent.LogEvent);
}
protected override void Write(LogEventInfo logEvent)
{
OnLog(this, logEvent.FormattedMessage);
}
// consider overriding WriteAsyncThreadSafe methods as well.
}
Usage in WPF Window Control
public partial class MainWindow
{
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private NlogMemoryTarget _nlogMemoryTarget;
public MainWindow()
{
InitializeComponent();
_nlogMemoryTarget = new NlogMemoryTarget("TextBoxOutput", LogLevel.Trace);
_nlogMemoryTarget.OnLog += LogText;
}
private void LogText(object sender, string message)
{
this.MessageView.AppendText($"{message}\n");
this.MessageView.ScrollToEnd();
}
private void DoSomething() {
logger.Trace("DoSomething called!");
}
}
When you call on DoSomething
(or do logger.Trace
), your overloaded methods in your memory target will execute - which raises the event OnLog
. Since you assigned an event handler, LogText
, to OnLog
in the construction of MainWindow
, it will execute.