unit ULog;
interface
uses
Classes;
type
TLogThread = class(TThread)
private
{ Private declarations }
private FLogFile:string;
private FTextList:TThreadList;
procedure DoWriteLog;
protected
procedure Execute; override;
public
constructor Create(AFileName:string);
procedure WriteLog(AText:String);
end;
implementation
uses SysUtils;
type
TLogLine=class
private
Text:String;
end;
{ TLogThread }
constructor TLogThread.Create(AFileName: string);
var
dir:string;
begin
FTextList:=TThreadList.Create;
dir:=SysUtils.ExtractFileDir(AFileName);
if not DirectoryExists(dir) then
ForceDirectories(dir);
if not FileExists(AFileName) then
begin
with TStringList.Create do
try
SaveToFile(AFileName);
finally
Free;
end;
end;
FLogFile:=AFileName;
FreeOnTerminate:=true;
Inherited Create(false);
end;
procedure TLogThread.DoWriteLog;
var
line:TLogLine;
list:TList;
logFile:Text;
begin
list:=FTextList.LockList;
try
if list.Count>0 then
begin
AssignFile(logFile,FLogFile);
Append(LogFile);
try
while list.Count>0 do
begin
line:=TLogLine(list[0]);
WriteLn(LogFile,line.Text);
list.Delete(0);
line.Free;
end;
Flush(logFile);
Close(logFile);
except
end;
end;
finally
FTextList.UnlockList;
end;
end;
procedure TLogThread.Execute;
begin
{ Place thread code here }
repeat
DoWriteLog;
if not Terminated then
sleep(100);
until self.Terminated;
DoWriteLog;
FTextList.Free;
end;
procedure TLogThread.WriteLog(AText: String);
var
line:TLogLine;
begin
line:=TLogLine.Create;
line.Text:=Format('%s %s',[formatdatetime('[HH:mm:ss:zzz]',now),AText]);
FTextList.Add(line);
end;
end.
一个可能是线程安全的日志记录类
最新推荐文章于 2025-05-20 17:14:42 发布