NLog控件到现有的RichTextBox Windows窗体 [英] NLog control to an existing RichTextBox Windows Form
问题描述
下面是我的NLog配置,我想将日志加载到Form1中名为rtMessage的现有RichTextBox中,但是NLog将创建一个新窗口,并将日志消息加载到RichTextBox中:
Below is my NLog configuration, I want to load log into existing RichTextBox called rtMessage in Form1, but NLog will create a new windows with log message loaded into the RichTextBox:
<targets>
<target xsi:type="RichTextBox" name="m" layout="${longdate}|${level:uppercase=true}|${logger}|${message}"
controlName="rtMessage" formName="Form1" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="m" />
</rules>
谢谢.
推荐答案
I think you can find the answer to your issue on the NLog Codeplex forum, here.
如果直接在Form1
表单内的字段声明中初始化static
logger
,则Form1
实例将不存在,并且NLog将继续创建新的RichTextBox
目标的表单.
If you initialize the static
logger
directly in the field declaration inside your Form1
form, the Form1
instance will not yet exist, and NLog will go on creating a new form for the RichTextBox
target.
您需要做的是将logger
的初始化延迟到已经初始化Form1
实例的时间,例如在Load
事件处理程序中.
What you need to do is delay the initialization of the logger
to a time when the Form1
instance is already initialized, for example in a Load
event handler.
以下是Codeplex问题的功能代码摘录:
Here is an excerpt of functional code from the Codeplex issue:
public partial class Form1 : Form
{
private static Logger logger;// = LogManager.GetCurrentClassLogger();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
logger = LogManager.GetCurrentClassLogger();
}
}
为避免不必要的重新初始化,您可能只想在logger
尚未初始化的情况下进行初始化,即
To avoid unnecessary re-initialization, you might want to initialize logger
only if it has not already been initialized, i.e.
private void Form1_Load(object sender, EventArgs e)
{
if (logger == null) logger = LogManager.GetCurrentClassLogger();
}
这篇关于NLog控件到现有的RichTextBox Windows窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!