一个可能是线程安全的日志记录类

本文深入探讨了一种高效的日志记录与线程管理方法,通过自定义线程类`TLogThread`,实现了日志的实时记录与多线程环境下日志的有序输出。该实现不仅确保了日志的准确性与及时性,还通过异步写入机制优化了系统性能。文章详细阐述了`TLogThread`类的设计原理、关键成员变量以及核心方法的实现逻辑,为开发者提供了一种实用的日志管理解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值