Mega Code Archive

 
Categories / Delphi / Files
 

Creating a logfile and append text to it

Title: Creating a logfile and append text to it Question: This is just some simple code for creating a log file and for append a text to it. Answer: const BreakingLine = '//----------------------------------------------------------------------------//'; //** This procedure just creates a new Logfile an appends when it was created ** procedure CreateLogfile; var T:TextFile; FN:String; begin // Getting the filename for the logfile (In this case the Filename is 'application-exename.log' FN := ChangeFileExt(Application.Exename, '.log'); // Assigns Filename to variable F AssignFile(F, FN); // Rewrites the file F Rewrite(F); // Open file for appending Append(F); // Write text to Textfile F WriteLn(F, BreakingLine); WriteLn(F, 'This Logfile was created on ' + DateTimToStr(Now); WriteLn(F, BreakingLine); WriteLn(F, ''); // finally close the file CloseFile(F); end; // Procedure for appending a Message to an existing logfile with current Date and Time ** procedure WriteToLog(aLogMessage:String); var T:TextFile; FN:String; begin // Getting the filename for the logfile (In this case the Filename is 'application-exename.log' FN := ChangeFileExt(Application.Exename, '.log'); //Checking for file if (not FileExists(FN)) then begin // if file is not available then create a new file CreateLogFile; end; // Assigns Filename to variable F AssignFile(F, FN); // start appending text AppendFile(F); //Write a new line with current date and message to the file WriteLn(F, DateTimeToStr(Now) + ': ' + aLogMessage); // Close file CloseFile(F) end;