且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

NLog控件到现有的RichTextBox Windows窗体

更新时间:2023-12-06 10:15:10

我认为您可以在NLog Codeplex论坛

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();
    }