Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NLog with WPF richtextbox

Tags:

c#

wpf

nlog

I have an application which has several tabs. I am trying to add logging with NLog where the output is directed to a richtextbox.

My main form is an instance of a class MyNamespace.MainWindow and its name is MainWindow1. It has a tab and in that tab I have a RichTextBox called rtbLogBox

I have imported WpfRichTextBox extension from NuGetand place this piece of code in the MainWindow class's loaded event

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        if(logger == null) logger = LogManager.GetCurrentClassLogger();

        WpfRichTextBoxTarget rtbTarget = new WpfRichTextBoxTarget
        {
            Name = "rtbLog",
            ControlName = "rtbLogBox",
            FormName = "MainWindow"
        };

        LogManager.Configuration.AddTarget(rtbTarget);


        LogManager.Configuration.AddRule(LogLevel.Info, LogLevel.Fatal, rtbTarget.Name);

        logger.Info("This");
    }

The problem is that this does not produce any outputs in the RichTextBox control.

I have an output to a file in addition to this and that target gets the log when I run the app.

like image 824
Ashkan Avatar asked Oct 30 '25 01:10

Ashkan


1 Answers

Since the logger is created before you are changing the LogManager's configuration, you need to notify the logger of the change.

Calling LogManager.ReconfigExistingLoggers() should do the trick.

Documentation is here.

like image 142
Vojtěch Frnoch Avatar answered Nov 01 '25 16:11

Vojtěch Frnoch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!