.net - 如何在 WPF 应用程序中使用 RichTextBox 作为 NLog 目标?

标签 .net wpf richtextbox target nlog

我阅读了以下帖子,但都没有帮助获得与 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/

相关文章:

c# - Winforms 托盘应用程序和 WM_CLOSE

c# - 我怎样才能执行我的应用程序的单个实例?

c# - 使用 LINQ 确定序列不包含任何元素

c# - 如何以编程方式设置 WPF DataGrid 的模板和填充内容?

c# - 删除 C# Flowdocument 元素之间的空格?

wpf - GetPositionAtOffset 仅对文本等效?

c# - 使用 NAudio 分割 Wav 文件会从每个部分中删除 1 秒

c# - 从 Alt+Tab 隐藏 WPF 表单

wpf - 根据PresentationFramework.Aero重写WPF TextBox中的默认样式。

c# - 如何通过 saveFiledialog 将 richboxtext 内容保存到 .txt 文件?