日志文件

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.
posted @ 2011-01-22 13:44  小阿枫  阅读(402)  评论(0编辑  收藏  举报