【问题标题】:How to read log-files over network real fast?如何通过网络快速读取日志文件?
【发布时间】:2010-12-06 15:39:22
【问题描述】:

我正在使用 Delphi 2007,并且有一个应用程序可以通过内部网络从多个位置读取日志文件并显示异常。这些目录有时包含数千个日志文件。应用程序可以选择仅读取最近 n 天的日志文件,它也可以在任何日期时间范围内。

问题是第一次读取日志目录时可能会非常慢(几分钟)。第二次速度要快得多。

我想知道如何优化我的代码以尽可能快地读取日志文件? 我正在使用 vCurrentFile: TStringList 将文件存储在内存中。 这是从 FileStream 更新的,因为我认为这更快。

这里有一些代码:

刷新:读取日志文件的主循环

// In this function the logfiles are searched for exceptions. If a exception is found it is stored in a object.
// The exceptions are then shown in the grid
procedure TfrmMain.Refresh;
var
  FileData : TSearchRec;  // Used for the file searching. Contains data of the file
  vPos, i, PathIndex : Integer;
  vCurrentFile: TStringList;
  vDate: TDateTime;
  vFileStream: TFileStream;
begin
  tvMain.DataController.RecordCount := 0;
  vCurrentFile := TStringList.Create;
  memCallStack.Clear;

  try
    for PathIndex := 0 to fPathList.Count - 1 do                      // Loop 0. This loops until all directories are searched through
    begin
      if (FindFirst (fPathList[PathIndex] + '\*.log', faAnyFile, FileData) = 0) then
      repeat                                                      // Loop 1. This loops while there are .log files in Folder (CurrentPath)
        vDate := FileDateToDateTime(FileData.Time);

        if chkLogNames.Items[PathIndex].Checked and FileDateInInterval(vDate) then
        begin
          tvMain.BeginUpdate;       // To speed up the grid - delays the guichange until EndUpdate

          fPathPlusFile := fPathList[PathIndex] + '\' + FileData.Name;
          vFileStream := TFileStream.Create(fPathPlusFile, fmShareDenyNone);
          vCurrentFile.LoadFromStream(vFileStream);

          fUser := FindDataInRow(vCurrentFile[0], 'User');          // FindData Returns the string after 'User' until ' '
          fComputer := FindDataInRow(vCurrentFile[0], 'Computer');  // FindData Returns the string after 'Computer' until ' '

          Application.ProcessMessages;                  // Give some priority to the User Interface

          if not CancelForm.IsCanceled then
          begin
            if rdException.Checked then
              for i := 0 to vCurrentFile.Count - 1 do
              begin
                vPos := AnsiPos(MainExceptionToFind, vCurrentFile[i]);
                if vPos > 0 then
                  UpdateView(vCurrentFile[i], i, MainException);

                vPos := AnsiPos(ExceptionHintToFind, vCurrentFile[i]);
                if vPos > 0 then
                  UpdateView(vCurrentFile[i], i, HintException);
              end
            else if rdOtherText.Checked then
              for i := 0 to vCurrentFile.Count - 1 do
              begin
                vPos := AnsiPos(txtTextToSearch.Text, vCurrentFile[i]);
                if vPos > 0 then
                  UpdateView(vCurrentFile[i], i, TextSearch)
              end
          end;

          vFileStream.Destroy;
          tvMain.EndUpdate;     // Now the Gui can be updated
        end;
      until(FindNext(FileData) <> 0) or (CancelForm.IsCanceled);     // End Loop 1
    end;                                                          // End Loop 0
  finally
    FreeAndNil(vCurrentFile);
  end;
end;

UpdateView 方法:向显示网格添加一行

{: Update the grid with one exception}
procedure TfrmMain.UpdateView(aLine: string; const aIndex, aType: Integer);
var
  vExceptionText: String;
  vDate: TDateTime;
begin
  if ExceptionDateInInterval(aLine, vDate) then     // Parse the date from the beginning of date
  begin
    if aType = MainException then
      vExceptionText := 'Exception'
    else if aType = HintException then
      vExceptionText := 'Exception Hint'
    else if aType = TextSearch then
      vExceptionText := 'Text Search';

    SetRow(aIndex, vDate, ExtractFilePath(fPathPlusFile), ExtractFileName(fPathPlusFile), fUser, fComputer, aLine, vExceptionText);
  end;
end;

判断行是否在日期范围内的方法:

{: This compare exact exception time against the filters
@desc 2 cases:    1. Last n days
                  2. From - to range}
function TfrmMain.ExceptionDateInInterval(var aTestLine: String; out aDateTime: TDateTime): Boolean;
var
  vtmpDate, vTmpTime: String;
  vDate, vTime: TDateTime;
  vIndex: Integer;
begin
  aDateTime := 0;
  vtmpDate := Copy(aTestLine, 0, 8);
  vTmpTime := Copy(aTestLine, 10, 9);

  Insert(DateSeparator, vtmpDate, 5);
  Insert(DateSeparator, vtmpDate, 8);

  if TryStrToDate(vtmpDate, vDate, fFormatSetting) and TryStrToTime(vTmpTime, vTime) then
    aDateTime := vDate + vTime;

  Result := (rdLatest.Checked and (aDateTime >= (Now - spnDateLast.Value))) or
            (rdInterval.Checked and (aDateTime>= dtpDateFrom.Date) and (aDateTime <= dtpDateTo.Date));

  if Result then
  begin
    vIndex := AnsiPos(']', aTestLine);

    if vIndex > 0 then
      Delete(aTestLine, 1, vIndex + 1);
  end;
end;

测试文件日期是否在范围内:

{: Returns true if the logtime is within filters range
@desc Purpose is to sort out logfiles that are no idea to parse (wrong day)}
function TfrmMain.FileDateInInterval(aFileTimeStamp: TDate): Boolean;
begin
  Result := (rdLatest.Checked and (Int(aFileTimeStamp) >= Int(Now - spnDateLast.Value))) or
            (rdInterval.Checked and (Int(aFileTimeStamp) >= Int(dtpDateFrom.Date)) and (Int(aFileTimeStamp) <= Int(dtpDateTo.Date)));
end;

【问题讨论】:

    标签: delphi logfiles logfile-analysis


    【解决方案1】:

    你想多快?如果你想真的很快,那么你需要使用除了 windows 网络之外的东西来读取文件。原因是如果您想读取日志文件的最后一行(或自上次读取后的所有行),则需要再次读取整个文件。

    在您的问题中,您说问题在于枚举目录列表很慢。那是你的第一个瓶颈。如果您想真正快速,则需要切换到 HTTP 或在存储日志文件的机器上添加某种日志服务器。

    使用 HTTP 的优点是您可以进行范围请求,并且只需获取自上次请求以来添加的日志文件的新行。这将真正提高性能,因为您传输的数据更少(尤其是在启用 HTTP 压缩的情况下),而且您在客户端处理的数据也更少。

    如果您添加某种类型的日志服务器,那么该服务器可以在服务器端进行处理,它可以在服务器端对数据进行本机访问,并且只返回日期范围内的行。一种简单的方法可能是将您的日志放入某种 SQL 数据库中,然后对其运行查询。

    那么,你想走多快?

    【讨论】:

    • 是的,我害怕程序代码中没有太多可做的事情。几年前我们实际上有一个项目将日志存储在数据库中并以 SQL 的形式访问它,但它从未完成。但是正如您所说,如果我们分配大量时间来准备服务器上的日志,我们可能会很快得到它。但这不是一个高优先级项目:) 无论如何感谢您的回答。
    • 通过更多的编码工作,您可以避免每次都读取整个文件。如果您只对文件的最后一部分感兴趣,您可以直接查找最后几 KB 并在那里阅读。
    【解决方案2】:

    问题不是你的逻辑,而是底层文件系统。

    当您将许多文件放在一个目录中时,大多数文件系统都会变得非常慢。这对 FAT 来说非常糟糕,但 NTFS 也会受到它的影响,尤其是当您的目录中有数千个文件时。

    您能做的最好的事情就是重新组织这些目录结构,例如按年龄。

    然后每个目录中最多有 100 个文件。

    --杰罗恩

    【讨论】:

    • 这是真的,但这就是现实。在我的情况下,很少搜索超过 30 天的文件,所以也许我应该通过预定的 bat 文件将旧文件移动到存档目录,加快搜索速度。
    • 第二次更快的原因是服务器现在已将信息缓存在内存中。因此,您无法从 Delphi 方面做任何事情来真正加速它(您可能能够稍微加快速度,但用户不会注意到效果)。所以最好的办法确实是将不再需要的文件归档。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 2019-04-25
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多