How to create Logfiles in Delphi?

Manytimes in your delphi project, you will require to print logfiles in order to track the flow of control. Here is a simple code snippet to print logfiles in delphi.

Code snippet

procedure TMyClass.CreateLogfile;
var
  aLine : string;
  aFileName : string;
  myFile : TextFile;
  aFilePath : string;
begin
  try
    aLine := 'The line which you want to print. You can change this line dynamically by passing   aLine as  parameter to CreateLogfile function';
    aFileName := 'MyLogfile_' + FormatDateTime('dd-mm-yyyy',Now)+'.log';
    aFilePath := 'C:\ProjectFolder\'+aFileName;
    AssignFile(myFile, aFilePath);
    if FileExists(aFilePath) then
      Append(myFile)
    else
      Rewrite(myFile);
    WriteLn(myFile, FormatDateTime('dd-mmm-yyyy hh:nn:ss.zzz',Now) + ': ' + ALine);
    Flush(myFile);
  finally
    CloseFile(myFile);
  end;
end;


Explanation: CreatLogfile function creates a logfile MyLogfile_TodaysDateTime.log at C:\ProjectFolder. If the logfile exists, it will append the line at the end otherwise it will create a new logfile and then writes to it. Logfile will be created new on everyday as the DateTime will get changed everyday. Thats why, DateTime is embedded with the name of logfiles. If you don't want to create a new logfile everyday, just remove the datetime field from the name of logfile and keep it simple like MyLogfile.log.

I think, you have understood my point. For any doubts, just inform me. I will be pleased to help you.