如何在WPF应用程序中使用NLog的RichTextBox Target? [英] How can I use NLog's RichTextBox Target in WPF application?

查看:657
本文介绍了如何在WPF应用程序中使用NLog的RichTextBox Target?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I use RichTextBox Target in WPF application? I don't want to have a separate window with log, I want all log messages to be outputted in richTextBox located in WPF dialog.

我尝试将WindowsFormsHost与RichTextBox框一起使用,但这对我不起作用:NLog仍然打开了单独的Windows窗体.

I've tried to use WindowsFormsHost with RichTextBox box inside but that does not worked for me: NLog opened separate Windows Form anyway.

推荐答案

如果在配置文件中定义RichTextBoxTarget,则会自动创建一个新表单.这是因为NLog会在您的(命名的)表单和控件创建之前初始化.即使您没有指向目标的任何规则.也许有更好的解决方案,但是我通过编程创建目标来解决了这个问题:

If you define a RichTextBoxTarget in the config file, a new form is automatically created. This is because NLog initializes before your (named) form and control has been created. Even if you haven't got any rules pointing to the target. Perhaps there is a better solution, but I solved it by creating the target programatically:

using NLog;
//[...]
RichTextBoxTarget target = new RichTextBoxTarget();
target.Name = "RichTextBox";
target.Layout = "${longdate} ${level:uppercase=true} ${logger} ${message}";
target.ControlName = "textbox1";
target.FormName = "Form1";
target.AutoScroll = true;
target.MaxLines = 10000;
target.UseDefaultRowColoringRules = false;
target.RowColoringRules.Add(
    new RichTextBoxRowColoringRule(
        "level == LogLevel.Trace", // condition
        "DarkGray", // font color
        "Control", // background color
        FontStyle.Regular
    )
);
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Debug", "Gray", "Control"));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Info", "ControlText", "Control"));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Warn", "DarkRed", "Control"));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Error", "White", "DarkRed", FontStyle.Bold));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Fatal", "Yellow", "DarkRed", FontStyle.Bold));

AsyncTargetWrapper asyncWrapper = new AsyncTargetWrapper();
asyncWrapper.Name = "AsyncRichTextBox";
asyncWrapper.WrappedTarget = target;

SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Trace);

这篇关于如何在WPF应用程序中使用NLog的RichTextBox Target?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆