zoukankan      html  css  js  c++  java
  • 日志文件

    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.
  • 相关阅读:
    使用C#实现DHT磁力搜索的BT种子后端管理程序+数据库设计(开源)
    便携版WinSCP在命令行下同步文件夹
    ffmpeg (ffprobe)分析文件关键帧时间点
    sqlite删除数据或者表后,回收数据库文件大小
    ubuntu 20.04下 freeswitch 配合 fail2ban 防恶意访问
    ffmpeg使用nvenc编码的结论记录
    PC版跑跑卡丁车 故事模式 亚瑟传说章节 卡美洛庆典 2阶段 心灵之眼 攻略
    There was an error loading or playing the video
    Nvidia RTX Voice 启动报错修复方法
    火狐浏览器 关闭跨域限制
  • 原文地址:https://www.cnblogs.com/doorsky/p/1941941.html
Copyright © 2011-2022 走看看