Wednesday, 9 May 2012

Writing log files for Applications in C# with time stamp

 A sample code which creates a log file (one per day & instance) 
and puts in time-stamped log entries into it. The file names are such 
that sorting them in Windows File Explorer is very easy for the SysAdmin
 
 
using System.IO;
public void WriteLogLine(string sCallerName, string sLogFolder, 
                        long lCallerInstance, string sLogLine)
{
  lock(this)
  {
    string sFileName;
    sFileName = String.Format("{0}_{1:yyyy.MM.dd}_{2:00}.log", 
                  sCallerName, DateTime.Now, lCallerInstance);
    StreamWriter swServerLog = 
           new StreamWriter(sLogFolder + sFileName, true);
    swServerLog.WriteLine(
           String.Format("[{0:T}] {1}", DateTime.Now, sLogLine));
    swServerLog.Close();
  }
}

1 comment:

  1. It would be lot better if your blog is more explanatory ...

    ReplyDelete