A simple way to log data to a text file

Posted: (EET/GMT+2)

 

I thought I'd share my simple piece of .NET Delphi code, as the code is often useful, but never at hand when needed.

The idea is that, for instance, in ASP.NET application it is difficult to know when things go wrong. For that reason, some logging is needed, and the simplest way to do this is to write the exception object data to a file.

But to write text to the file is the question. What is the simplest way to do it? I think the following procedure is quite likely it:

Procedure LogMessageToFile(Msg : String);
Var
  SW   : System.IO.StreamWriter;
  Text : String;

begin
  SW := System.IO.File.AppendText(
    'C:\Temp\logfile.txt');
  Try
    Text := System.String.Format(
      '{0:G}: {1}.',System.DateTime.Now,Msg);
    SW.WriteLine(Text);
    System.Console.WriteLine(Text);
  Finally
    SW.Close();
  End;
end;