Short background story…
How to do that with Grails?
grails create-filters info.rnowak.App.Basket
class BasketFilters {
def filters = {
all(controller:'*', action:'*') {
before = {
}
after = { Map model ->
}
afterView = { Exception e ->
}
}
}
}
All we need to do is fill empty closures, modify filter properties and put some data into MDC.
all is the general name of our filter, as class BasketFilters (plural!) can contain many various filters. You can name it whatever you want, for this post let assume it will be named basketFilter. Another thing is change of filter parameters. According to official documentation (link) we can customize our filter in many ways. You can specify controller to be filtered, its actions, filtered urls and so on. In our example you can stay with default option where filter is applied to every action of every controller. If you are interested in filtering only some urls, use uri parameter with expression describing desired urls to be filtered. Three closures that are already defined in template have their function and they are started in these conditions:
- before – as name says, it is executed before filtered action takes place
- after – similarly, it is called after the action
- afterView – called after rendering of the actions view
Putting something into MDC in filter
class BasketFilters {
def filters = {
basketFilter(controller:'*', action:'*') {
before = {
MDC.put("basketNumber", params.basketNumber ?: "")
}
after = { Map model ->
MDC.remove("basketNumber")
}
}
}
}
So we are putting something into MDC. But how make use of it in logs?
def conversionPattern = "%d{yyyy-MM-dd HH:mm:ss} %-5p %t [%c{1}] %X{basketNumber} - %m%n"
And that’s it :) We’ve put custom data in log4j MDC and successfully used it in logs to display interesting values.