LogToFile procedure
Return to Introduction  Previous page  Next page
Unit
acUtils  

Declaration
procedure LogToFile(const FileName, Str: String; AddDateTime: Boolean = True; AddLineBreak: Boolean = True);  

Description
The LogToFile procedure adds a new string (Str parameter) to the file specified by FileName parameter.  
 
Optionally you can specify whether each line which about to be written should contain the current date and time (AddDateTime parameter), and whether you want to separate lines with CRLF characters (AddLineBreak parameter).  

Example
procedure TMainForm.Log(const St: String);  
begin  
  if OutputLog1.Checked and not (csDestroying in ComponentState) then  
    LogMemo.Lines.Add(DateTimeToStr(Now) + ' ' + St);  
 
  if LogToFile1.Checked and not (csDestroying in ComponentState) then  
    LogToFile('C:\Logs\MyLog.log', St);  
end;  

Original code
procedure LogToFile(const FileName, Str: String;  
  AddDateTime: Boolean {$IFDEF D4} = True {$ENDIF};  
  AddLineBreak: Boolean {$IFDEF D4} = True {$ENDIF});  
var  
  FileHandle: hFile;  
  Dummy: DWord;  
  DTSt: String;  
begin  
  FileHandle := CreateFile(PChar(FileName), GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil,  
                           OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);  
  if FileHandle <> INVALID_HANDLE_VALUE then  
   begin  
    SetFilePointer(FileHandle, 0nil, FILE_END);  
    if AddDateTime then  
     begin  
      DTSt := '[' + DateTimeToStr(Now) + '] ';  
      WriteFile(FileHandle, DTSt[1], Length(DTSt), Dummy, nil);  
     end;  
    WriteFile(FileHandle, Str[1], Length(Str), Dummy, nil);  
    if AddLineBreak then  
      WriteFile(FileHandle, CRLF, 2, Dummy, nil);  
    FlushFileBuffers(FileHandle);    
    CloseHandle(FileHandle);  
   end;  
end;  

See also
Wait procedure.