我如何使用一个RichTextBox作为NLOG目标在WPF应用程序?如何使用、应用程序、目标、NLOG

由网友(暮冬-  Gentle°)分享简介:我阅读下面的职位,但既不是帮助刚刚得到NLOG打印日志同样有效的方式到一个RichTextBox控制目标中的WinForms。I read the following posts but neither helped to just get the same efficient way of printing log...

我阅读下面的职位,但既不是帮助刚刚得到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.

How我可以在WPF应用程序中使用NLOG的RichTextBox的目标?

WPF:绑定的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 ();
        });
    }
}
阅读全文

相关推荐

最新文章