gpt4 book ai didi

Delphi:如何在不使用断言的情况下获取(当前代码行,当前单元,当前函数)?

转载 作者:行者123 更新时间:2023-12-03 15:03:32 30 4
gpt4 key购买 nike

我正在尝试在我的程序上创建一个日志系统,它将在文本文件上记录调试消息,并且我想保存代码中调用日志消息的确切位置,但我不想使用 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 - 并在另一个地方调用它,因为该行始终是相同的文件名也将是 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

请帮忙,提前致谢。

最佳答案

您可以绑定(bind)自己的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;

关于Delphi:如何在不使用断言的情况下获取(当前代码行,当前单元,当前函数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16459608/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com