在RichTextBox中显示NLog跟踪

时间:2015-12-17 17:44:59

标签: c# .net richtextbox nlog

我想在app执行的同时将NLog跟踪显示到RichTextBox

logger.Trace("This is a Trace message");
logger.Debug("This is a Debug message");
logger.Info("This is an Info message");
logger.Warn("This is a Warn message");
logger.Error("This is an Error message");
logger.Fatal("This is a Fatal error message");

是否有NLog任何全局事件,因此可以使用它并填充RichTextBox

谢谢!

1 个答案:

答案 0 :(得分:5)

我们必须安装https://www.nuget.org/packages/NLog.Windows.Forms

使用后NLog.Windows.Forms;

最后添加代码

 private void FormMain_Load(object sender, EventArgs e)
        {
            NLog.Windows.Forms.RichTextBoxTarget target = new NLog.Windows.Forms.RichTextBoxTarget();
            target.Name = "RichTextBox";
            target.Layout = "${longdate} ${level:uppercase=true} ${logger} ${message}";
            target.ControlName = "richTextBoxMainLog";
            target.FormName = "FormMain";
            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);
        }

您还需要配置NLog目标。

 <target xsi:type="RichTextBox"
            name="target2"
            layout="${message} ${rtb-link:link text in config}"

            formName="Form1"
            ControlName="richTextBoxMainLog"
            autoScroll="true"
            maxLines="20"

            allowAccessoryFormCreation="false"
            messageRetention="OnlyMissed"

            supportLinks="true"

            useDefaultRowColoringRules="true" />

下载示例项目并对其进行测试https://github.com/NLog/NLog.Windows.Forms