加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Delphi – 从每秒更改的日志文件中读取

发布时间:2020-12-15 09:07:01 所属栏目:大数据 来源:网络整理
导读:我需要从另一个应用程序不断更改的.log文件中读取. (经常添加更多数据) 所以我从头开始: var LogFile: TStrings; Stream: TStream; begin LogFile := TStringList.Create; try Stream := TFileStream.Create(Log,fmOpenRead or fmShareDenyNone); try LogFi
我需要从另一个应用程序不断更改的.log文件中读取. (经常添加更多数据)

所以我从头开始:

var
    LogFile: TStrings;
    Stream: TStream;
   begin
   LogFile := TStringList.Create;
   try
      Stream := TFileStream.Create(Log,fmOpenRead or fmShareDenyNone);
      try
         LogFile.LoadFromStream(Stream);
      finally
         Stream.Free;
      end;

      while LogFile.Count > Memo1.Lines.Count do
      Memo1.Lines.Add(LogFile[Memo1.Lines.Count]);
   finally
      LogFile.Free;
   end;
end;

这完全没问题.它会在添加数据的同时实时更新备忘录.但是,我想要在备忘录中看到一些添加的数据.我希望不添加这些行,但仍然可以在没有垃圾线的情况下实时更新备忘录.

最好的方法是什么?

解决方法

您显然需要检查该行是否包含您要包含的内容,并且仅在具有该内容时添加该内容(如果您不想包含该内容,则不添加它,无论哪种情况).跟踪之前处理的LogFile中的最后一行也会更有效率,因此每次都可以跳过这些行 – 如果您将变量设置为表单本身的私有成员,它将自动初始化为0当你的申请开始时:

type
  TForm1 = class(TForm)
    //... other stuff added by IDE
  private
    LastLine: Integer;
  end;


// At the point you need to add the logfile to the memo
for i := LastLine to LogFile.Count - 1 do
begin
  if ContentWanted(LogFile[i]) then
    Memo1.Lines.Append(LogFile[i]);
  Inc(LastLine);
end;

所以要完全根据你的代码处理这个问题:

type
  TForm1 = class(TForm)
    //... IDE stuff here
  private
    FLastLogLine: Integer;
    procedure ProcessLogFile;
  public
    // Other stuff
  end;

procedure TForm1.ProcessLogFile;
var
  Log: TStringList;
  LogStream: TFileStream;
  i: Integer;
begin
  Log := TStringList.Create;
  try
    LogStream := TFileStream.Create(...);
    try
      Log.LoadFromStream(LogStream);
    finally
      LogStream.Free;
    end;

    for i := FLastLogLine to Log.Count - 1 do
      if Pos('[Globals] []',Log[i]) <>0 then
        Memo1.Lines.Append(Log[i]);

    // We've now processed all the lines in Log. Save
    // the last line we processed as the starting point
    // for the next pass.
    FLastLogLine := Log.Count - 1;      
  finally
    Log.Free;
  end;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  Timer1.Enabled := False;
  try
    ProcessLogFile;
  finally
    Timer1.Enabled := True;
  end;
end;
end;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读