Simple text logging for a C# console application

Simple logging to text file into a directory called ‘logs’ inside the directory of the executing image.

private static object objLock = new object();

public static void LogInfo(string d)
{
   var sb = new StringBuilder();
   sb.AppendFormat("INFO : {0} {1}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"), Environment.NewLine);
   sb.Append(d);
   Log(sb.ToString());
}

public static void LogError(Exception ex)
{
   var sb = new StringBuilder();
   sb.AppendFormat("EXCEPTION : {0} {1}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"), Environment.NewLine);
   sb.AppendFormat("{0}{1}", ex.Message, Environment.NewLine);
   sb.AppendFormat("{0}{1}", ex.StackTrace, Environment.NewLine);
   Log(sb.ToString());
}

static void Log(string d)
{
   Console.WriteLine(d);
   var _logsDir = "logs";

   if (!Directory.Exists(_logsDir))
      Directory.CreateDirectory(_logsDir);

   lock (objLock)
   {
      var path = Path.Combine("logs", LogFileName());
      using (StreamWriter sw = new StreamWriter(path, true))
      {
         sw.WriteLine(d);
         sw.WriteLine(" ");
         sw.Close();
      }
   }
}

static string LogFileName()
{
   return DateTime.Now.ToString("ddMMyyyy") + ".log";
}

Leave a Reply