我如何使用一个RichTextBox作为NLOG目标在WPF应用程序? [英] How can I use a RichTextBox as a NLog Target in a WPF application?
问题描述
我阅读下面的职位,但既不是帮助刚刚得到NLOG打印日志同样有效的方式到一个RichTextBox控制目标中的WinForms。
I read the following posts but neither helped to just get the same efficient way of printing logs from NLog onto a RichTextBox control target as in Winforms.
<一个href="http://stackoverflow.com/questions/3705480/how-can-i-use-nlogs-richtextbox-target-in-wpf-application">How我可以在WPF应用程序中使用NLOG的RichTextBox的目标?
我也浏览了官方论坛,但没有成功(但建议阅读上面这两个职位)。
I also browsed the official forum but with no success (except suggestions to read the two above posts).
这个想法是添加目标为:
The idea would be to add the target as:
<target xsi:type="RichTextBox" name="console"
layout="${longdate:useUTC=true}|${level:uppercase=true}|${logger}::${message}"
autoScroll="true"
maxLines="1000000"
controlName="rtbConsole"
formName="MyWPFWindowName"
useDefaultRowColoringRules="true">
</target>
和WPF的窗口MyWPFWindowName姓名中,添加一个RichTextBox控制rtbConsole。即使我创建目标的winow已被载入编程后,它不会使用现有的rtbConsole而是创建一种新的形式。
And within the WPF window with MyWPFWindowName as name, to add a RichTextBox control with rtbConsole. Even if I create the target programmatically after the winow has been loaded, it will not use the existing rtbConsole but create a new form.
那么,你的帮助是AP preciated!
So, your help is appreciated!
推荐答案
我创建了一个自定义NLOG目标并将其链接到一个文本框。
I created a custom NLog target and linked it to a text box.
public class NlogMemoryTarget : Target
{
public Action<string> Log = delegate { };
public NlogMemoryTarget (string name, LogLevel level)
{
LogManager.Configuration.AddTarget (name, this);
SimpleConfigurator.ConfigureForTargetLogging (this, level);
}
protected override void Write (AsyncLogEventInfo[] logEvents)
{
foreach (var logEvent in logEvents) {
Write (logEvent);
}
}
protected override void Write (AsyncLogEventInfo logEvent)
{
Write (logEvent.LogEvent);
}
protected override void Write (LogEventInfo logEvent)
{
Log (logEvent.FormattedMessage);
}
}
public partial class MainWindow
{
private NlogMemoryTarget _Target;
public MainWindow ()
{
InitializeComponent ();
this.Loaded += (s, e) => {
_Target = new NlogMemoryTarget ("text box output", LogLevel.Trace);
_Target.Log += log => LogText (log);
};
}
private void LogText (string message)
{
this.Dispatcher.Invoke ((Action) delegate () {
this.MessageView.AppendText (message + "\n");
this.MessageView.ScrollToEnd ();
});
}
}
这篇关于我如何使用一个RichTextBox作为NLOG目标在WPF应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!