我正在尝试在我的程序上创建一个日志系统,该系统将在文本文件上记录调试消息,并且我想保存调用日志消息的代码中的确切位置,但我不想使用 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
请帮助,并在此先感谢。