Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 753
G.Rose Avatar asked Dec 07 '25 10:12

G.Rose


1 Answers

Write it to the application scope, in onRequestStart(), include the following code:

lock scope="application" type="exclusive" timeout=1 throwontimeout=false {
    if (!application.keyExists("reqCount") {
        application.reqCount= 0;
    }
    application.reqCount++;
}

Then you can use it whereever you need it.

like image 197
Redtopia Avatar answered Dec 10 '25 01:12

Redtopia