中间件的日志类

{*******************************************************}
{
单元名: 日志
版权:
作者:    陈新光
日期:    2015-10-17
说明:
更新历史:
}
{*******************************************************}

unit untLog;

interface

uses
  SysUtils, vcl.forms, System.Classes, SyncObjs;

Type
  TLog = Class(TThread)
  private
    FLogList: TStringList;
    FCS: TCriticalSection;
    procedure WriteToFile(const Msg: string);
    function GetLogFileName: String;
  protected
    procedure Execute; override;
  public
    Constructor Create overload;
    Destructor Destroy; override;
    procedure WriteLog(const Str: String);
  end;

var
  Log: TLog;

implementation

{ TLogObj }

function TLog.GetLogFileName: String;
var
  Logpath: String;
begin
  Logpath := ExtractFilePath(Application.ExeName) + 'Logs\';
  if not DirectoryExists(Logpath) then
    ForceDirectories(Logpath);
  Result := Logpath + FormatDateTime('YYYY-MM-DD', Now) + '.log';
end;

constructor TLog.Create;
begin
  inherited Create(False);
  FreeOnTerminate := False;
  FLogList := TStringList.Create;
  FCS := TCriticalSection.Create;
end;

destructor TLog.Destroy;
begin
  FLogList.Free;
  FCS.Free;
  inherited;
end;

procedure TLog.Execute;
var
  i: Integer;
begin
  inherited;
  while not Self.Terminated do
  begin
    Sleep(30000);
    if FLogList.Count > 0 then
    begin
      FCS.Enter;
      try
        for i := 0 to FLogList.Count - 1 do
        begin
          WriteToFile(FLogList.Strings[i]);
        end;
        FLogList.Clear;
      finally
        FCS.Leave;
      end;
    end;
  end;
end;

procedure TLog.WriteLog(const Str: String);
begin
  FCS.Enter;
  try
    FLogList.Add(Str);
  finally
    FCS.Leave;
  end;
end;

procedure TLog.WriteToFile(const Msg: string);
var
  FileName: String;
  FileHandle: TextFile;
begin
  FileName := GetLogFileName;
  Assignfile(FileHandle, FileName);
  try
    if FileExists(FileName) then
      Append(FileHandle)
    else
      ReWrite(FileHandle);

    WriteLn(FileHandle, FormatDateTime('[HH:MM:SS]', Now) + '  ' + Msg);
  finally
    CloseFile(FileHandle);
  end;
end;

end.

posted @   delphi中间件  阅读(724)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示