Custom log writer in C#

Custom logging using C# in .NET application

Target Audience : Beginner

Log writing is considered as an essential function in any software application. You can monitor how your software is behaving and also you can identify errors and performance issues using logs. A good log writer can save a lot of time for investigations when you face an issue in your application. There are lots of logging tools available for .NET applications such as Logging Application Block. They have their own pros and cons. In this article I’m going to write a custom logging function which is very simple. I used .NET 4.7.2 in this project but it doesn’t depend on the .NET framework version much, so you can use this custom logging function with earlier .NET versions too.

First create a console application using Visual Studio.

Main program

Then add a new class to the project. I gave the name “LogWriter” to the new class.

logging writer class added

Now make the new class “static”.  Since the custom logging function performs a common functionality and we don’t want to create objects each time we call the logging, we make it static. So .NET CLR will automatically load the instance for us whenever we need it.

Then we have to specify where the log files should be stored. We can use app settings to store the log files path.

Go to App.config file and add below section inside the <configuration> section.

<appSettings>
<add key="LogFile" value="YourPath\Logs" />
</appSettings>

Add a static method inside the LogWriter class to perform the custom logging function.

LogWriter class

public static void LogActivity(string message, string status = "")
{
try
{
}
catch (Exception ex)
{
throw ex;
}
}

We are going to pass two string parameters to this function, message and status. And we are using a try catch block.

Inside the try catch block we are doing the custom logging function. Now we have to read the log files path from the app settings.

string LogFolderPath = ConfigurationManager.AppSettings["LogFile"];
if (string.IsNullOrEmpty(LogFolderPath))
{
LogFolderPath = Environment.CurrentDirectory;
}
if (!Directory.Exists(LogFolderPath))
{
DirectoryInfo di = Directory.CreateDirectory(LogFolderPath);
}

To use the ConfigurationManager.AppSettings we have to add the System.Configuration reference to the project.

Then add using statements for System.Configuration and System.IO.

If the app setting is missing, it will create the log folder inside the application folder.

Now add below code to create a date based file name.

string date = DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
string dateFolder = Path.Combine(LogFolderPath, date);
LogFolderPath = dateFolder + ".txt";

This will create separate log files for each day.

We can format the logs as below based on our requirements.

string Msg = "";
Msg = "\n---------------------------- Start -----------------------------------\n" + Environment.NewLine;
Msg += "Time : " + DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + Environment.NewLine;
Msg += "Status : " + status + Environment.NewLine;
Msg += "Message : " + message + Environment.NewLine;
Msg += "\n---------------------------- End -----------------------------------\n" + Environment.NewLine;

Next step is to write a method to put the logs into the actual file.

public static void Log(string sFilePath, string sErrMsg)
{
StreamWriter sw;
try
{
sw = File.AppendText(sFilePath);
sw.WriteLine(sErrMsg);
sw.Flush();
sw.Close();
}
catch (Exception ex)
{
throw ex;
}
}

Now we can call the new method inside our LogActivity method.

Log(LogFolderPath, Msg);

Its done! We can call this method inside the Main method as below.

static void Main(string[] args)
{
LogWriter.LogActivity("Starting custom logging", "OK");
}

Since LogWriter is a static class, We dont have to create objects of the class. So Just use LogWriter.LogActivity()

Below you can find the full code for the LogWriter class.

using System;
using System.Configuration;
using System.Globalization;
using System.IO;namespace LogWriter
{
public static class LogWriter
{
public static void LogActivity(string message, string status = "")
{
try
{
string LogFolderPath = ConfigurationManager.AppSettings["LogFile"];
if (string.IsNullOrEmpty(LogFolderPath))
{
LogFolderPath = Environment.CurrentDirectory;
}
if (!Directory.Exists(LogFolderPath))
{
DirectoryInfo di = Directory.CreateDirectory(LogFolderPath);
}

string date = DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
string dateFolder = Path.Combine(LogFolderPath, date);
LogFolderPath = dateFolder + ".txt";
string Msg = "";
Msg = "\n---------------------------- Start -----------------------------------\n" + Environment.NewLine;
Msg += "Time : " + DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + Environment.NewLine;
Msg += "Status : " + status + Environment.NewLine;
Msg += "Message : " + message + Environment.NewLine;
Msg += "\n---------------------------- End -----------------------------------\n" + Environment.NewLine;
Log(LogFolderPath, Msg);
}
catch (Exception ex)
{
throw ex;
}
}
public static void Log(string sFilePath, string sErrMsg)
{
StreamWriter sw;
try
{
sw = File.AppendText(sFilePath);
sw.WriteLine(sErrMsg);
sw.Flush();
sw.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}
}

When we check the created log file it will be like below.

logs

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.