Create Text log file – Simplest way possible

No comments

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)
 string path = Directory.GetCurrentDirectory();
 path = path + "\\Logs\\";

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

 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 :


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.


Hope this helps!



Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

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