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

2023-11-21

我阅读了以下文章,但都没有帮助获得与 Winforms 中相同的有效方式将日志从 NLog 打印到 RichTextBox 控制目标。

如何在 WPF 应用程序中使用 NLog 的 RichTextBox Target?

WPF:将 RichTextBox 绑定到记录器输出

我也浏览了官方论坛,但没有成功(除了建议阅读上述两篇文章)。

这个想法是将目标添加为:

<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 ();
        });
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 WPF 应用程序中使用 RichTextBox 作为 NLog 目标? 的相关文章

随机推荐