Examples Delphi

This code shows one way to save much things that's going on in your application in a log file.
Here are two files present, the project file and one unit that does the work...
{Unit1.pas}
unit Unit1;
interface
uses
{$DEFINE DEBUG}
{$IFDEF DEBUG} uLog, {$ENDIF}
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
var
Bar: Integer;
begin
Bar := 100;
{$IFDEF DEBUG}
Log(Format('Button1.Click; Bar = %d',[Bar]));
{$ENDIF}
end;
end.
//--------------------------------------------------------------------
{uLog.pas}
unit uLog;
interface
procedure Log(S: String);
implementation
uses
Windows, SysUtils;
var
LogFile: TextFile;
LogCriticalSection: TRtlCriticalSection;
procedure Log(S: String);
var
SystemTime: TSystemTime;
FileTime: TFileTime;
begin
GetSystemTime(SystemTime);
SystemTimeToFileTime(SystemTime, FileTime);
EnterCriticalSection(LogCriticalSection);
WriteLn(LogFile, Format('%s %.8x%.8x %s',
[FormatDateTime('yy.mm.dd hh.mm.ss', Now),
FileTime.dwHighDateTime, FileTime.dwLowDateTime, S]));
LeaveCriticalSection(LogCriticalSection);
end;
procedure Startup;
var
FileName: String;
begin
InitializeCriticalSection(LogCriticalSection);
FileName := Format('Log file for %s at %s.txt',
[ParamStr(0), DateTimeToStr(Now)]);
while Pos(':', FileName) > 0 do FileName[Pos(':', FileName)] := '.';
while Pos('/', FileName) > 0 do FileName[Pos('/', FileName)] := '-';
while Pos('\', FileName) > 0 do FileName[Pos('\', FileName)] := '.';
AssignFile(LogFile, FileName);
Rewrite(LogFile);
end;
procedure Shutdown;
begin
CloseFile(LogFile);
DeleteCriticalSection(LogCriticalSection);
end;
initialization
Startup;
finalization
Shutdown;
end.