NLog control to an existing RichTextBox Windows Form

Viewed 11278

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>

Thank you.

5 Answers

Here are three tips to help you load log in existing RichTextBox.

  1. Ensure formName and controlName is consistent with the actual use
  2. Set allowAccessoryFormCreation="False" in NLog.config
  3. RichTextBoxTarget.ReInitializeAllTextboxes(this); in Form_Load

PS:Follow this way, you neeed to config your RichTextBoxTarget in NLog.config, please refer RictTextBoxTarget.

Don't forget to add

LogManager.ReconfigExistingLoggers();

if setting the richtextbox as a logger programmatically

https://github.com/NLog/NLog.Windows.Forms/wiki/RichTextBoxTarget

I have the similar problems to nlog into the windows.form. I used the NLog.Windows.Forms from the Nugget with the Nlog, and Nlog.config. I follow that given templatefrom the link and make it work without any manual initialisation. I provide part of the code into the Nlog.config. Hope it helps.

<targets>
<target xsi:type="RichTextBox"
      name="richTextBox1"
      layout="${longdate}|${level:uppercase=true}|${logger}|${message}"
      height="30"
      autoScroll="true"
      maxLines="60"
      showMinimized="true"
      toolWindow="true"
      controlName="richTextBox1"
      formName="Form1"
      width="50"
      useDefaultRowColoringRules="true"
      allowAccessoryFormCreation="true"
      messageRetention="None"
      supportLinks="false"
>
</target>
</targets>
Related