We saw in my previous blog that SLF4J and SimpleLogger support the most critical logging requirements with ease. In this blog, we will see how to use SLF4J in a Servlets based application.
The general practice is to initialize logging related objects and parameters at the startup of an application. In case of Servlets, any of the servlet in the Web Application can be invoked due to user action. So we need to use a different technique for initializing logging related objects.
The first step is to implement the ServletContextListener. Here is a Java class that implements the ServletContextListener interface.
The next step is to add an annotation called @WebListener. This is already shown in the above code snippet.
Now when you package and deploy your Servlets based Web Application, you will see that SLF4J Logger (SimpleLogger) has been appropriately initialized. And you should be able to use the SLF4J Logger classes in the rest of your Web Application code.
Here is the analysis of what happened behind the screen as a result of these two steps
- With Servlets 3.0 specification we can use annotation such as @WebListener to annotate a class to be a Servlets event listener. The container will examine the event listeners interfaces implemented by the class to decide how to associate the listener class.
- Any class that implements ServletContextListener receives events when the whole Web Application is deployed and initialized.
- When the application is deployed, the container (Tomcat for example) will create an instance of the listener class and associate it with the ServletContext.
- When you invoke getLogger of LoggerFactory for the first time, internally an instance of SimpleLogger class is created
- SimpleLogger uses private static variables to store different log parameters such as Log Level, date format etc.
- These log parameters are initialized only when the first instance of class _SimpleLogger _is created.
- In our example this initialization of log parameters happens as part of the contextIntialized method which is invoked at the start of our Web Application.
- When other application Servlets are loaded and executed, the subsequent calls to getLogger result in the reuse of the various log parameters that were initialized earlier (static variables).