Creating a Simple User Log with ColdFusion

I needed a quick and dirty way to log users to a page on one of my sites.  It was easy enough to do with Adobe ColdFusion, and I am sure this can be modified and done just as easily in other languages.

STEP 1: Create an empty text file Called userlog.txt
This file would be best located in a secure (non-web accessible) directory, but for simplicity I am placing it the same directory as the page that will be tracked.

STEP 2: Define the log string 
This is the string of text that you will want each time the page is read.  It should be placed in a conspicuous location on the ColdFusion file that you want to track. The string should be comma-delimited so that you could open your file in your favorite spreadsheet program.  You can customize the columns that you would like to track but here is an example:

   pagename, [optionselected…,] user IP, date/time

You can also record things like your user’s browser and OS information. In the third step (below) this line will be written to your log file each time the page is loaded, so it should stay relatively simple.  Here is the code I used:

<cfset UserLogData = ‘landing page 1, ’ & form.optionfield & ‘, ’ &  
   cgi.REMOTE_ADDR & ‘, ’ & DateFormat(Now(),’mm/dd/yyyy’) & ’ ’ &
   TimeFormat(now(),’hh:mm:ss’)>


STEP 3: Write the log string to your log file.
Now that you have the values that you want to write to your log file (written to a variable called UserLogData) you simply append the new log string to the file you created in STEP 1.

<cffile action=”APPEND” file=”#ExpandPath(‘Userlog.txt’)#”  
  output=”#UserLogData#” addnewline=”Yes”> 

You will now be able to download this file and view in your favorite spreadsheet program at any time.    I would suggest deleting the contents of this file regularly, since it can fill up pretty fast.

Good Luck!


Short URL for this post: http://tmblr.co/ZVAV4y3Fv7v9