Ashkan
Ashkan

Reputation: 1085

Using NLog with WPF richtextbox

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.

Upvotes: 4

Views: 6078

Answers (2)

Dominic Jonas
Dominic Jonas

Reputation: 5005

You can also use my wpf control. (https://github.com/dojo90/NLogViewer). There is also a nuget package available.

enter image description here

Upvotes: 4

Vojtěch Frnoch
Vojtěch Frnoch

Reputation: 96

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.

Upvotes: 4

Related Questions