Ratpacked: Request Logging
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:
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:
Written with Ratpack 1.0.0.