Ratpacked: Request Logging
Ratpack has a special log request handler. Here's a request logging tutorial, featuring a Groovy DSL definition.
Join the DZone community and get the full member experience.
Join For FreeRatpack comes with a special handler to log requests in the common log or NCSA format. We need the (default) interfaceratpack.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!'
}
}
}
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments