Find who's calling the method

白昼怎懂夜的黑 提交于 2019-12-08 15:45:14

问题


I'd like to somehow find out which CFC is calling my method.

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.

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?

Thanks in advance


回答1:


Update: As Richard Tingle's answer points out, since CF10 you can use CallStackGet(), which is better than throwing a dummy exception.


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.

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()
    });
  }
}



回答2:


From ColdFusion 10 there is now a function to do this callStackGet()

For example the following code will dump the stack trace to D:/web/cfdump.txt

<cfdump var="#callStackGet()#" output="D:/web/cfdump.txt">



回答3:


One kludgey way is to throw/catch a custom error and parse the stack trace. Here are some examples

  • http://www.bennadel.com/blog/406-Determining-Which-Function-Called-This-Function-Using-ColdFusion-.htm
  • http://coldfusion.dzone.com/news/what-function-called-my-functi



回答4:


I don't know of a method to do directly what you are asking, maybe someone else does.

However, I believe you could get the stack trace and create a function to parse the last method call.

This function on cflib will get you the stack trace.



来源:https://stackoverflow.com/questions/2674619/find-whos-calling-the-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!