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

标签 wpf richtextbox nlog

如何在 WPF 应用程序中使用 RichTextBox Target? 我不想有一个带有日志的单独窗口,我希望所有日志消息都输出在 WPF 对话框中的 richTextBox 中。

我尝试将 WindowsFormsHost 与 RichTextBox 框一起使用,但这对我不起作用:NLog 无论如何都打开了单独的 Windows 窗体。

最佳答案

同时,解决方法是使用可用的 3 个类 here ,然后按照以下步骤操作:

  1. 将 3 个文件导入到您的项目中

  2. 如果还没有这种情况,请使用 Project > Add Reference添加对 WPF 程序集的引用:WindowsBase, PresentationCore, PresentationFramework .

  3. WpfRichTextBoxTarget.cs ,将第 188-203 行替换为:

        //this.TargetRichTextBox.Invoke(new DelSendTheMessageToRichTextBox(this.SendTheMessageToRichTextBox), new object[] { logMessage, matchingRule });
        if (System.Windows.Application.Current.Dispatcher.CheckAccess() == false) {
            System.Windows.Application.Current.Dispatcher.Invoke(new Action(() => {
                SendTheMessageToRichTextBox(logMessage, matchingRule);
            }));
        }
        else {
            SendTheMessageToRichTextBox(logMessage, matchingRule);
        }
    }
    
    private static Color GetColorFromString(string color, Brush defaultColor) {
        if (defaultColor == null) return Color.FromRgb(255, 255, 255); // This will set default background colour to white.
        if (color == "Empty") {
            return (Color)colorConverter.ConvertFrom(defaultColor);
        }
    
        return (Color)colorConverter.ConvertFromString(color);
    }
    
  4. 在您的代码中,配置新目标,如下例所示:

我希望它有所帮助,但它似乎绝对不是一个全面的实现......

public void loading() {
    var target = new WpfRichTextBoxTarget();
    target.Name = "console";
    target.Layout = "${longdate:useUTC=true}|${level:uppercase=true}|${logger}::${message}";
    target.ControlName = "rtbConsole"; // Name of the richtextbox control already on your window
    target.FormName = "MonitorWindow"; // Name of your window where there is the richtextbox, but it seems it will not really be taken into account, the application mainwindow will be used instead.
    target.AutoScroll = true;
    target.MaxLines = 100000;
    target.UseDefaultRowColoringRules = true;
    AsyncTargetWrapper asyncWrapper = new AsyncTargetWrapper();
    asyncWrapper.Name = "console";
    asyncWrapper.WrappedTarget = target;
    SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Trace);
}

关于wpf - 如何在 WPF 应用程序中使用 NLog 的 RichTextBox Target?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3705480/

相关文章:

c# - 使 ListBox 大小适合用作 ItemsPresenter 的 ItemsPanel

c# - InvalidOperationException 未处理 - WPF 路径

wpf - 向 WPF 换行面板添加换行符/换行符

c# - richTextbox1 到 textbox1?

c# - 如何在我的 ASP.NET Core MVC 应用程序中记录来自类库的 NLog 调用?

c# - NLog 文件目标和 keepFileOpen 标志

wpf - MVVM 和多窗口

wpf - 底部垂直滚动richtextbox [WPF]

c# - RichTextBox 项目符号缩进(.NET 窗体)

mysql - NLog mySQL 数据库作为目标配置