中间件的日志类

时间:2023-01-03 03:54:37

{*******************************************************}
{
单元名: 日志
版权:
作者:    陈新光
日期:    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.