【原创】Delphi 线程写日志

unit uMain;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);

  private
  type
    TMyLog = class(TThread)
    private      
      F: String;
    public
      constructor Create(AText:String);
      procedure Execute; override;
      destructor Destroy; override;
    end;
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

var
  FPath: String= '';
  
  FCs: TRTLCriticalSection; 
  
// 日志函数 

procedure WriteLog(const AText: String);
var
  F: TextFile;
  AFile: String;
begin
  try
    AFile:= FPath + 'Logs.txt';
    AssignFile(F,  AFile);
    if not FileExists(AFile) then begin
      Rewrite(F);
    end;
    Append(F);
    Writeln(F, AText);
    CloseFile(F);
  except
  end;
end;


//创建线程
procedure TForm1.Button1Click(Sender: TObject);
var
  a,b,c,d,e: TMyLog;
begin  //  
  InitializeCriticalSection(FCs);  
              
  a:= TMyLog.Create('AAAAA');
  b:= TMyLog.Create('BBBBB');
  c:= TMyLog.Create('CCCCC');
  d:= TMyLog.Create('DDDDD');
  e:= TMyLog.Create('EEEEE');     
  
  A.Start;
  B.Start;
  C.Start;
  D.Start;
  E.Start;      
  
//  DeleteCriticalSection(FCs);
  
end;         
procedure TForm1.FormCreate(Sender: TObject);
begin
  FPath:= ExtractFilePath( ParamStr(0) );
end;


{ TForm1.TMyLog }

constructor TForm1.TMyLog.Create(AText:String);
begin
  inherited Create(True);          
  F:= AText;
end;

destructor TForm1.TMyLog.Destroy;
begin   
  inherited;
end;

procedure TForm1.TMyLog.Execute;
begin
  inherited;
  
  while true do begin    
  
        EnterCriticalSection(FCs);  //进入临界区,对资源进行保护
        try
          WriteLog(F+' 测试线程 :'+FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', Now));  
        finally
          LeaveCriticalSection(FCs); 
        end; 
        sleep(1);                
  end;
  
end;

end.
 

添加新评论

纯文本

  • 不允许使用HTML标签。
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。
请输入图片中的字符,不区分大小写