Log4j in Spring mvc controllers: how to remove duplication

In every controller I have a line like this in my Spring MVC webapp:

static Logger logger = Logger.getLogger(ControllerName.class);

      

This is a slight overlap. How can I write logged controllers without repeating this line every time?

thank

+3


source to share


2 answers


You might not like it, but one of the things I love about Project Lombok is. You can annotate your class with @ Log4j (or better, @ Slf4j) to get an invisible Logger named log .



+1


source


The first suggestion is to have a common base class for all controllers with the following line:

public abstract class AbstractBaseController {

    protected Logger logger = Logger.getLogger(this.getClass());

}

      

Please note that the logger is no longer static

- this is not a problem with singleton Spring services / controllers, but still I find it a little awkward. See Also: Why Are We Declaring Static Loggers Finalists?



Also it goes against OO principles a bit and doesn't let you inherit anything else. This is actually a limitation of the Java language, in Scala / You can write:

class SomeController extends BaseController with Logging 

      

Where BaseController

is the base class, and Logging

is the property that is mixed in the logger

field with the class SomeController

. Very comfortably.

0


source







All Articles