Dialecticus
Dialecticus

Reputation: 16761

Set NLog RichTextBox target in configuration

I want to use NLog to log messages to existing rich text box. Up to now I used code approach, given in this answer, but I found out this codeplex issue that explains how I can use configuration after all. Problem is, it does not work, separate rich text box window is still opened. My project is WPF, window name and control name are set in xaml like this:

<Window x:Name="Main_Window" ...>
    ...
    <DockPanel ...>
        ...
        <RichTextBox x:Name="rtbLog" ... />
    </DockPanel>
</Window>

and they are used in Nlog.config like this:

<target xsi:type="RichTextBox"
        formName="Main_Window" controlName="rtbLog" ... />

So, names match. I set the logger in Window_Loaded event handler:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    log = LogManager.GetCurrentClassLogger();
}

What am I doing wrong?

Upvotes: 2

Views: 2779

Answers (1)

nemesv
nemesv

Reputation: 139768

The RichTextBoxTarget cannot work correctly in a WPF application because it is only supports Winforms.

If you check the source code of getting the configured form you will see:

    protected override void InitializeTarget()
    {
        if (this.FormName == null)
        {
            this.FormName = "NLogForm" + Guid.NewGuid().ToString("N");
        }

        var openFormByName = Application.OpenForms[this.FormName];
    //...

Where the Application.OpenForms method is the Winforms way of looking for and opening Windows/Forms.

It was proposed numerous times to add a WpfRichTextBox to the core NLog:

But so for the only option is to use a community created WpfRichTextBoxTarget which can be accessed as a nuget package:

NLog WPF Rich Text Logger Target

Upvotes: 4

Related Questions