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

时间:2011-07-07 22:04:34

标签: .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>

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

所以,感谢您的帮助!

4 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:4)

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

答案 2 :(得分:2)

正如@mafu的回答所暗示的:

  

[创建]自定义NLog [内存] Target,然后将其链接到TextBox

此示例将通过event和事件处理程序委托“链接”它。

将NLog内存目标定义为Type

public class NlogMemoryTarget : Target
{
    public event EventHandler<string> OnLog;

    public NlogMemoryTarget(string name, LogLevel level) : this(name, level, level) {}
    public NlogMemoryTarget(string name, LogLevel minLevel, LogLevel maxLevel)
    {
        // important: we want LogManager.Configuration property assign behaviors \ magic to occur
        //   see: https://stackoverflow.com/a/3603571/1366179
        var config = LogManager.Configuration;

        // Add Target and Rule to their respective collections
        config.AddTarget(name, this);
        config.LoggingRules.Add(new LoggingRule("*", minLevel, maxLevel, this));

        LogManager.Configuration = config;
    }

    [Obsolete]
    protected override void Write(AsyncLogEventInfo[] logEvents)
    {
        foreach (var logEvent in logEvents) {
            Write(logEvent.LogEvent);
        }
    }

    protected override void Write(AsyncLogEventInfo logEvent)
    {
        Write(logEvent.LogEvent);
    }

    protected override void Write(LogEventInfo logEvent)
    {
        OnLog(this, logEvent.FormattedMessage);
    }

    // consider overriding WriteAsyncThreadSafe methods as well.
}

在WPF窗口控件中的用法

public partial class MainWindow
{
    private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

    private NlogMemoryTarget _nlogMemoryTarget;

    public MainWindow()
    {
        InitializeComponent();

        _nlogMemoryTarget = new NlogMemoryTarget("TextBoxOutput", LogLevel.Trace);
        _nlogMemoryTarget.OnLog += LogText;
    }

    private void LogText(object sender, string message)
    {
        this.MessageView.AppendText($"{message}\n");
        this.MessageView.ScrollToEnd();
    }

    private void DoSomething() {
       logger.Trace("DoSomething called!");
    }
}

当您调用DoSomething(或执行logger.Trace)时,将执行内存目标中的重载方法-这将引发事件OnLog。由于您在LogText的构造中将事件处理程序OnLog分配给MainWindow,因此它将执行。

答案 3 :(得分:0)

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

以下是我的尝试:

Write a custom (WPF) control target 使用类似于NLog的FormControlTarget的算法。

Ensure to register your new target
此外,NLog的FormHelper可能会有所帮助。

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