Controlling Logging using App.Config (.NET)

Its been a while since I last did a blog post, so I’m going to blog something straight-forward in simple to get back into the habit. I’ve got a number of ideas for future blog posts but I’m currently struggling to find the time to write them.

We’ve an application at work that proving difficult to track down exactly the scenarios that customers are performing in order to get their application into ‘unique’ states. I think there are more fundamental issues with the application, but a good starting point for at least learning more would be to add some basic logging, so I’m going to cover a very basic blog post for how to add a very simple logging mechanism and then control it via the app.config of the application.

Please note, rather than rolling your own logging mechanism, consider using Log4Net, which is a port of log4j. It might take a little time to get it configured correctly but the functionality it offers is second-to-none.

The Application – Starting Point

I decided to go with a WinForms application – with 2 buttons, one to write to the log file, and one to Exit.

image

The code behind the form is incredibly simple. I’ve created a class that will do my Logging for me (Logger) and the code for this will follow the form class. The form class creates an instance of the Logger class, and then handles the button clicks.

Source code for Form1.cs

    public partial class Form1 : Form
    {
        private Logger MyLogger = null;

        public Form1()
        {
            InitializeComponent();
            MyLogger = new Logger();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnDoLog_Click(object sender, EventArgs e)
        {
            MyLogger.WriteToLog("Testing 1...2...3");
        }
    }

Source code for Logger.cs

        public void WriteToLog(string msg)
        {
                File.AppendAllText(@".\Log.txt", msg + Environment.NewLine);
        }

The Logger class only contains one method at the moment, namely WriteToLog, which will append the string given to the log file.

Building and running this application, and clicking on the Log Something button should give you some text in the Log.txt file in alongside you executable.

Controlling Logging

Next I’m going to disable and enable the logging using the app.config. For this I need to add an Application Configuration File (right click on project, add new item and then select Application Configuration File from the dialog box – leave the name as App.config).

image

Now we need to add an appSettings area to the App.config file, and supply a key/value pair. My final xml looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="LoggingEnabled" value="False" />
  </appSettings>
</configuration>

Next we need to add the System.Configuration referecne to the project – again right click on the project and select Add Reference… and then search for the System.Configuration assembly.

In the Logger.cs class, we use the ConfigurationManager to read the value of the LoggingEnabled value from the App.config, see the following code:

using System;
using System.Configuration;
using System.IO;

namespace LoggingExample
{
    public class Logger
    {
        public void WriteToLog(string msg)
        {
            bool loggingEnabled = Convert.ToBoolean(ConfigurationManager.AppSettings["LoggingEnabled"]);

            if (loggingEnabled)
            {
                File.AppendAllText(@".\Log.txt", msg + Environment.NewLine);
            }
        }
    }
}

Running the application now and clicking the Log Something button a few times, you’ll see no additional text is appended to the log file (remember, there will be at least one line already present from the previous run if you did that).

Enabled Logging – No Code Changes Required

Now to re-enable logging, browse to the directory containing your application. Open the LoggingExample.exe.config file using a text editor and simply change the value of the LoggingEnabled to True. Save this file, restart the application and ensure logging info is written to the log file.

Conclusion

Very simple to do, but Log4Net offers so much extra functionality. This example should also be enhanced to control the granularity of the logging to various levels (SEVERE, ERROR, WARNING, INFO, DEBUG etc…) and also the ConfigurationManager should only be read once, presumably in the logging classes constructor. This code isn’t meant for an deployment environment.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s