I have spent a lot of time over the course of my career writing ColdFusion code and during that time I have leveraged a lot of tools to monitor the health of my code. Tools for ColdFusion range from complex like Fusion Reactor for realtime application performance monitoring to the mundane with a simple
writeDump. One of my favorite ways of debugging is using the old standby, the writeLog function.
Getting to know writeLog
Writelog has been around since ColdFusion 9 and is supported by all the major application engines. The default log file consists of six columns: type, thread, date, time, application, and message. It is super simple to use:
writeLog(type = "error", message = "Oh no! There was an error", file = "my-errors");
This will either append a new log entry to my-errors.log in your servers log file directory if it exists, otherwise it will create the file and then append the message. The log files themselves are straight forward CSV delimited data. The column headers are in the first row and the data follows.
The data has been written out, now we just need a way to to make it useful. I will be using the kisdigital-playground repo since a basic application groundwork has already been laid.
The readLogfile reads the contents of the requested log file using cfhttp and then split into lines using listToArray on the fileContent using char 10 (new line) as the delimiter. Next, the log file attributes are appended to the lines array along with the epoch value that is derived from the date and time. Finally the array is sorted by epoch time in descending order and returned.
The next step is to create a simple view to output the data. In the Demo.cfc controller I am creating a new
readLog handler to call the LogService and save the output to the logs variable in the private request context.
To simplify things I have created an example log file in my payloads repo. There may be an easy way to expose the log directory in CommandBox, but I do not know offhand how to do it.
It is also possible to view the contents of the log file as an API JSON response.
I suppose the biggest caveat of leveraging this service, the log files have to be in a location readable from ColdFusion. However, when it does work it works really well.
I would be interested to hear how you handle debugging applications. Please feel free to share in the comments below!