Erik Sapir Erik Sapir - 3 months ago 37
Groovy Question

Grails: Printing how long each request took

I would like to print for each request in my controllers, when the request started, when it ended and how long was the process. Do i have to add this code to each request separately or is there any generic way to do that?

Answer

Besides the wide variety of plugins that exist (Profiler for example) a very simple solution is to use a filter. This blog post walks you through the process of setting up a filter that will log the start and end times for each controller action.

A very simple example using a Grails filter would be:

class PerfFilter {
  def filters = {
    profiler(controller: '*', action: '*') {
      before {
        request._startTime = System.currentTimeMillis()
        log.trace("Beginning ${controllerName} ${actionName}")
      }
      after {
        log.trace("Finished ${controllerName} ${actionName}")
        log.trace("Total time to execute was: ${System.currentTimeMillis() - request._startTime}")
      }
    }
  }
}

If you need something more robust for overall performance monitoring I highly recommend the Javamelody plugin for Grails.

Comments