Search code examples
coldfusionlifecycleapplication.cfccoldfusion-2016

Counting the number of hits in a life cycle method using ColdFusion


I am needing to display some analytics regarding how many times a "OnRequestStart" function is called, or rather the number of hits per hour on our internal API that’s contained in a .cfc file. Preferably through the life cycle method; however the counter must continue outside of the life cycle. I know this can be done easily in other languages, but I am new to ColdFusion and have been trying to read through the documentation to see if there is some form of life cycle method I can use in order to achieve this. If there are any sort of documentation I am missing (I've tried learn cf in a week, cfdocs, adobe documentation), but there's not really much out there. This probably isn’t 100% clear, but if there is any clarification needed I’ll be happy to help.

Edit: I figured it would be best to set an application variable in onApplicationStart and incrementally add 1 to the counter variable within the onRequest start. Here is my example code:

Application.cfc:

<CFFUNCTION NAME="OnApplicationStart" ACCESS="PUBLIC" RETURNTYPE="BOOLEAN">
   <cfset Application.timer EQ 0/>
   <cfset Application.counter EQ 0/>
</CFFUNCTION>

somepage.cfm

<tr> 
    <cfoutput> #Application.counter#</cfoutput>
</tr>

I thought this would work, but I get an error saying Element COUNTER is undefined in APPLICATION. Is there something I am missing? I tried to restart the CF server service and web server, but no luck.

Thank you everyone for your help


Solution

  • Turns out, the simplest way to do this is to simply create a variable either outside of the lifecycle or within onApplicationStart then increment the variable with each onRequestStart. You can then do whatever is needed after that. One thing I did stupidly was put <cfset Application.timer EQ 0/> <cfset Application.counter EQ 0/> after a <cfreturn> tag. Lesson learned, don't assume anything, research everything haha.

    Thank you everyone