我阅读了以下帖子,但都没有帮助获得与 Winforms 中相同的将日志从 NLog 打印到 RichTextBox 控件目标的有效方法。
How can I use NLog's RichTextBox Target in WPF application?
WPF: Binding RichTextBox to Logger Output
我也浏览了官方论坛,但没有成功(除了阅读上述两个帖子的建议)。
这个想法是将目标添加为:
<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>
并在以 MyWPFWindowName 为名称的 WPF 窗口中,添加带有 rtbConsole 的 RichTextBox 控件。即使我在加载 winow 后以编程方式创建目标,它也不会使用现有的 rtbConsole 而是创建一个新表单。
因此,感谢您的帮助!
最佳答案
我创建了一个自定义 NLog 目标并将其链接到一个文本框。
public class NlogMemoryTarget : Target
{
public Action<string> Log = delegate { };
public NlogMemoryTarget (string name, LogLevel level)
{
LogManager.Configuration.AddTarget (name, this);
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", level, this));//This will ensure that exsiting rules are not overwritten
LogManager.Configuration.Reload(); //This is important statement to reload all applied settings
//SimpleConfigurator.ConfigureForTargetLogging (this, level); //use this if you are intending to use only NlogMemoryTarget rule
}
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 ();
});
}
}
关于.net - 如何在 WPF 应用程序中使用 RichTextBox 作为 NLog 目标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6617689/