日志文件

本文介绍了一个使用Delphi编写的日志管理类,该类能够自动清理过期日志,支持格式化输出,适用于多模块系统,确保日志路径清晰,避免文件冲突。

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

delphi 写日志文件的一个类, 从网上查找的资料, 然后按自己的需求修正了下.

使用: 引用本单元后, 调用WriteLog函数即可. 默认31天清理一次日志.

unit uProgLog;

interface

uses
  Windows, SysUtils, SyncObjs;

type
  TLogFile = class
  private
    FLogKeepDays: Integer; //日志保存时间
    FLogPath: string;      //日志保存路径

    FCsWriteLogFile: TCriticalSection;
    FLogFile: TextFile;    //日志文件句柄
    FLogOpened: Boolean;   //日志文件是否打开
    FFileTime: TDateTime; //当前日志文件创建或打开时间
  protected
  public
    function WriteLogFile(const szFormat: string;const Args: array of const): Boolean;
    function DeleteLogFile(): Boolean;
    constructor Create();
    Destructor Destroy(); override;
  end;

  procedure WriteLog(const szFormat: string; const Args: array of const);
var
  gLog: TLogFile=nil;
  
implementation

uses DateUtils;
  
procedure WriteLog(const szFormat: string; const Args: array of const);
begin
  if gLog = nil then
    gLog := TLogFile.Create();
  gLog.WriteLogFile(szFormat,Args);
end;

{ TLogFile }

constructor TLogFile.Create();
var
  sLogName: string;
begin
  FLogOpened := False;
  FCsWriteLogFile := TCriticalSection.Create;

  FLogKeepDays := 31;
  sLogName := ExtractFileName(ParamStr(0));
  sLogName := Copy(sLogName,1,Pos('.',sLogName)-1);
//  if sLogName <> '' then
    //eg; D:\MYfile\myexelog\2009-03-05.log
    //防止同一系统中模块过多, 路径混乱
  FLogPath := ExtractFilePath(ParamStr(0))+ 'Log\'+sLogName+'\'
//  else FLogPath := ExtractFilePath(ParamStr(0))+ 'Log\';
end;

function TLogFile.DeleteLogFile(): Boolean;
var
  SearchRec: TSearchRec;
  FileMask: string;
  LocalFileTime: TFileTime;
  FileTime: Integer;
begin
  FileMask := FLogPath + '*.log';
  Result := FindFirst(FileMask, faAnyFile, SearchRec) = 0;
  try
    if Result then
    begin
      repeat
        if (SearchRec.Name[1] <> '.')
          and (SearchRec.Attr and faDirectory <> faDirectory) then
        begin
          FileTimeToLocalFileTime(SearchRec.FindData.ftCreationTime, LocalFileTime);
          FileTimeToDosDateTime(LocalFileTime, LongRec(FileTime).Hi, LongRec(FileTime).Lo);
          // 按照文件创建日期删除文件
          if FileDateToDateTime(FileTime) <= (Now() - FLogKeepDays) then
            DeleteFile(FLogPath + SearchRec.Name);
        end;
      until FindNext(SearchRec) <> 0;
    end;
  finally
    FindClose(SearchRec);
  end;
end;

destructor TLogFile.Destroy;
begin
  if (FLogOpened) then CloseFile(FLogFile);
  FCsWriteLogFile.Free();
  inherited;
end;

function TLogFile.WriteLogFile(const szFormat: string;
  const Args: array of const): Boolean;
var
  sFileName: string;
  dtCurrent: TDateTime;
  sBuffer: string;
  szDate: string;
begin
  Result := false;
  FCsWriteLogFile.Enter();
  try
    dtCurrent := Now(); //注意这里得到的是local time
    szDate := FormatDateTime('YYYYMMDD',dtCurrent);
    try
      if (FLogOpened)
         and (DateOf(dtCurrent) <> DateOf(FFileTime)) then
      begin
        CloseFile(FLogFile);
        FLogOpened := False;
        //每月15日 清理日志
        if Copy(szDate,7,2) = '15' then
          DeleteLogFile();
      end;

      if (not FLogOpened) then
      begin
        if not DirectoryExists(FLogPath) then
          if not ForceDirectories(FLogPath) then exit;
        sFileName := FLogPath + szDate+'.log';
        Assignfile(FLogFile, sFileName);
        
        try
          if FileExists(sFileName) then
            append(FLogFile)
          else rewrite(FLogFile);
          FLogOpened := True;
        except
          FLogOpened := False;
          Exit;
        end;
        FFileTime := dtCurrent;
      end;

      if FLogOpened then
      begin
        sBuffer := FormatDateTime('HH:MM:SS',dtCurrent) + '  ' +szFormat;
        sBuffer := Format(sBuffer, Args);
        writeln(FLogFile, sBuffer);
      end;
    except
      OutputDebugString('Write Log Exception');
    end;
  finally
    FCsWriteLogFile.Leave; //离开临界区
  end;
  Result := true;
end;

initialization

finalization
  if gLog <> nil then
    FreeAndNil(gLog);
end.

转载于:https://www.cnblogs.com/doorsky/archive/2011/01/22/1941941.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值