Create Text log file – Simplest way possible

We all need to log errors, information, warnings when writing your console application.

while there are several third party tools/methods available which you use in your solution such as Nlog, Log4net… etc. I would still prefer to create my custom code to generate the log file and capture all details as those tools might work on some machine and on some wont also depends badly on the permissions on the system.

below is simple code that i use :

using System;
using System.IO;

namespace YourNameSpace
{
 public static class ErrorLog
 {

public static void Logger(string ErrorCode, string ErrorMsg)
 {
 try
 {
 string path = Directory.GetCurrentDirectory();
 path = path + "\\Logs\\";

// check if directory exists
 if (!Directory.Exists(path))
 {
 Directory.CreateDirectory(path);
 }
 path = path + DateTime.Today.ToString("dd-MMM-yy") + ".log";
 // check if file exist
 if (!File.Exists(path))
 {
 File.Create(path).Dispose();
 }
 // log the error now
 using (StreamWriter writer = File.AppendText(path))
 {
 string error = "\n" + DateTime.Now.ToString() + ":" + ErrorCode + ":" + ErrorMsg;
 writer.WriteLine(error);
 writer.Flush();
 writer.Close();
 }

}
 catch (Exception ex)
 {
 throw new Exception(ex.Message);
 }
 }
 }
}

add this file to your code and later you can use it in your solution anywhere like below :

 ErrorLog.Logger("Info","yourtexthere");

kindly note that this will generate the logs file on your directory where the code is running in that case in the “BIN” folder. You can tweak the code to put it somewhere else if you need.

logs

Hope this helps!

Cheers!

Advertisement