查找谁在调用方法 [英] Find who's calling the method
问题描述
我想以某种方式找出哪个CFC正在调用我的方法.
I'd like to somehow find out which CFC is calling my method.
我有一个日志记录的CFC,许多不同的CFC都调用它.在此日志记录CFC上,需要存储调用该日志的CFC.
I have a logging CFC which is called by many different CFC's. On this logging CFC there's a need to store which CFC called for the log.
虽然我可以简单地将CFC名称作为参数传递给我的log.cfc,但我发现这是重复性的任务,如果我能以某种方式找出谁"在日志中调用该方法,则可能没有必要. cfc
Whilst I could simply pass the CFC name as an argument to my log.cfc, I find this to be a repetitive task, that might not be necessary, if I somehow could find out "who's" calling the method on log.cfc
有没有程序化的方式来实现这一目标?
Is there any programmatic way of achieving this?
预先感谢
推荐答案
更新:如 Richard Tingle的回答指出,由于CF10,您可以使用
Update: As Richard Tingle's answer points out, since CF10 you can use CallStackGet(), which is better than throwing a dummy exception.
原始答案:最简单的方法是抛出一个虚拟异常并立即捕获它.但这具有使虚拟异常显示在调试输出中的缺点.对我而言,这是一个破坏交易的行为,因此我编写了以下代码(基于在cflib上的此代码).我想创建一个类似于cfcatch对象的对象,以便可以在需要cfcatch对象的地方使用它.
Original answer: The easiest way is to throw a dummy exception and immediately catch it. But this has the downside of making a dummy exception show up in your debug output. For me, this was a deal-breaker, so I wrote the following code (based off of this code on cflib). I wanted to create an object that is similar to a cfcatch object, so that I could use it in places that expected a cfcatch object.
注意:您可能需要稍微调整一下此代码才能使其在CF8或更早的版本中工作.我认为在CF9之前不支持用于创建对象的{...}
语法.
Note: You may have to adjust this code a bit to make it work in CF8 or earlier. I don't think the {...}
syntax for creating object was supported prior to CF9.
StackTrace = {
Type= 'StackTrace',
Detail= '',
Message= 'This is not a real exception. It is only used to generate debugging information.',
TagContext= ArrayNew(1)
};
j = CreateObject("java","java.lang.Thread").currentThread().getStackTrace();
for (i=1; i LTE ArrayLen(j); i++)
{
if(REFindNoCase("\.cf[cm]$", j[i].getFileName())) {
ArrayAppend(StackTrace.TagContext, {
Line= j[i].getLineNumber(),
Column= 0,
Template= j[i].getFileName()
});
}
}
这篇关于查找谁在调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!