gpt4 book ai didi

c# - 在 RichTextBox 中显示 NLog 跟踪

转载 作者:太空宇宙 更新时间:2023-11-03 19:55:18 26 4
gpt4 key购买 nike

我想在应用程序执行时同时显示 NLog trace 到 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

谢谢!

最佳答案

我们必须安装 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

关于c# - 在 RichTextBox 中显示 NLog 跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34341007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com