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

Erw*_*yer 7 .net wpf nlog richtextbox target

我阅读了以下帖子但是没有帮助我们像在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>
Run Code Online (Sandbox Code Playgroud)

在具有MyWPFWindowName作为名称的WPF窗口中,使用rtbConsole添加RichTextBox控件.即使我在加载winow后以编程方式创建目标,它也不会使用现有的rtbConsole,而是创建一个新表单.

所以,感谢您的帮助!

maf*_*afu 9

我创建了一个自定义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 ();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)


Sya*_*hya 6

虽然这并不能真正回答你的问题,但我相信这个解决方案更好。用于在列表视图中显示 NLog 日志的 wpf 控件。https://github.com/erizet/NlogViewer


Jak*_*ger 0

我同意问题中的 2 个引用链接不是最佳的。(我也不会使用这些解决方案。)

这是我要尝试的:

使用类似于 NLog 的FormControlTarget的算法编写自定义 (WPF) 控制目标

确保注册您的新目标
另外,NLog 的FormHelper可能会有所帮助。

大多数 WinForms 代码应该可以轻松转换为 WPF。