5

我正在尝试在我的程序上创建一个日志系统,该系统将在文本文件上记录调试消息,并且我想保存调用日志消息的代码中的确切位置,但我不想使用 Assert 函数,因为它创建异常,这个系统不仅仅用于记录异常,我还必须写一些调试信息。

使用断言的示例:

procedure AnyProcedure();
begin
  try
    Assert(1=0);
  except
    on E: Exception do
      Log.AddLine('Log occurred is '+E.Message+' : Start');//Log occurred is "c:\progr~..jkdj.pas" at line [29]
  end;

  //....some code
  try
    Assert(1=0);
  except
    on E: Exception do
      Log.AddLine('Log occurred is '+E.Message+' : Step1 done');//Log occurred is "c:\progr~..jkdj.pas" at line [37]
  end;

  //....some code
  try
    Assert(1=0);
  except
    on E: Exception do
      Log.AddLine('Log occurred is '+E.Message+' : Step2 done');//Log occurred is "c:\progr~..jkdj.pas" at line [45]
  end;

  //....some code
  try
    Assert(1=0);
  except
    on E: Exception do
      Log.AddLine('Log occurred is '+E.Message+' : Step3 done');//Log occurred is  "c:\progr~..jkdj.pas" at line [53]
  end;

  //....some code
  try
    Assert(1=0);
  except
    on E: Exception do
      Log.AddLine('Log '+E.Message+' : End');//Log occurred is "c:\progr~..jkdj.pas" at line [61]
  end;
end;

这工作正常,它引发异常并且代码变得太大,所以我不能使用函数 - 请参阅下一个示例函数 LogMessage - 并在另一个地方调用它,因为该行也总是相同的文件name 将是 LogMessage 函数实现的位置:

不工作的例子:

procedure LogMessage(AMessage: String);
var AFile, ALine: String;
begin
  try
    Assert(1=0);             //line 29
  except
    on E: Exception do
    begin
      AFile:= Copy(E.Message, Pos(' (', E.Message)+2, Pos(', line ', E.Message)-Pos(' (', E.Message)-2);
      ALine:= Copy(E.Message, Pos(', line ', E.Message)+7, Pos(')', E.Message)-Pos(', line ', E.Message)-7);
      ShowMessage('Log occurred in file "'+AFile+'" at line ['+ALine+'] : '+AMessage);
    end;
  end;
end;

procedure AnyProcedure();
begin
  LogMessage('Start'); //Log occurred in file "c:\progr~....jkashdj.pas" at line [29]
//....
  LogMessage('step1'); //Log occurred in file "c:\progr~....jkashdj.pas" at line [29]
//....
  LogMessage('step2'); //Log occurred in file "c:\progr~....jkashdj.pas" at line [29]
//....
  LogMessage('step3'); //Log occurred in file "c:\progr~....jkashdj.pas" at line [29]
//....
  LogMessage('end');
end

请帮助,并在此先感谢。

4

2 回答 2

10

您可以将自己的TAssertErrorProc过程绑定到AssertErrorProc变量。你可能会这样写:

procedure OnAssert(const Message, Filename: string; LineNumber: Integer;
  ErrorAddr: Pointer);
begin
  ShowMessage(Format('Assert in file "%s" at line %d.', [Filename, LineNumber]));
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  AssertErrorProc := OnAssert;
end;
于 2013-05-09T10:42:42.043 回答
9

从指令指针映射到单元名称和行号的最简单方法是使用各种调试库之一:madExcept、EurekaLog、JclDebug 等。

这些工具都依赖于链接器生成的详细映射文件。尽管这些库以从意外异常生成错误报告而闻名,但它们具有您需要的所有功能。

于 2013-05-09T10:51:45.297 回答