Ratpack comes with a special handler to log requests in the common log or NCSA format. We need the (default) interface ratpack.handling.RequestLogger
which has a method ncsa
that returns a handler instance capable of logging our request data.
In the following example code we have a Groovy DSL definition of our Ratpack application. We use the all
method to add the request logger. The RequestLogger
implementation will make sure the complete handler chain is finished before logging the information.
import ratpack.handling.RequestLogger import static ratpack.groovy.Groovy.ratpack ratpack { handlers { // Here we add the request logger // for logging our request information // in common log or NCSA format. all(RequestLogger.ncsa()) get { render 'Ratpack rules!' } } }
When we run our application with logging enabled we get the following sample output when we request the /
path of our application:
[ratpack-compute-5-16] INFO ratpack.request - 0:0:0:0:0:0:0:1 - - [12/Oct/2015:08:57:59 +0200] "GET / HTTP/1.1" 200 - id=133aef4a-2abe-acc0-90a3-783826bad515
We see the request method, path and status code and we see Ratpack adds a unique request identifier to our requests and it is also logged with our request logger. The default logger name is ratpack.request
. We can use this to for example redirect the request logging to a file using the configuration of a SLF4J logging implementation. To change the logger implementation we can give our own as an argument for the ncsa
method:
import org.slf4j.Logger import org.slf4j.LoggerFactory import ratpack.handling.RequestLogger import static ratpack.groovy.Groovy.ratpack ratpack { // Create custom Logger implementation for request logging. final Logger requestLogger = LoggerFactory.getLogger('com.mrhaki.sample.requestLogger') handlers { // Instruct NCSA request logger to use // our requestLogger Logger implementation. all(RequestLogger.ncsa(requestLogger)) get { render 'Ratpack rules!' } } }
If we look at the logging output we see our custom logger name:
[ratpack-compute-13-2] INFO com.mrhaki.sample.requestLogger - 0:0:0:0:0:0:0:1 - - [12/Oct/2015:09:34:26 +0200] "GET / HTTP/1.1" 200 - id=81f996a6-bb41-f683-60e1-1ab19c11a14e
Written with Ratpack 1.0.0.