Quantcast
Channel: C2B2 Blog
Viewing all articles
Browse latest Browse all 223

Alternative Logging Frameworks for Application Servers: Tomcat

$
0
0
The final part of the blog series has finally arrived, this time covering Tomcat. Once more, we will be covering the basics on configuring it to use Log4j2 and SLF4J with Logback as the logger for a sample web application.

The previous entries in this series can be found by following these links:
The environment used for this blog was a 64-bit Linux VM, JDK Hotspot 8u25, Tomcat 5.0.15, Log4j 2.1, logback 1.1.2, slf4j 1.7.7, and NetBeans 8.0.1 as my IDE.

Under the assumption that you’ve already downloaded and installed all that you need, let’s begin…

Log4j2

We’ll configure Tomcat to use Log4j2 on a per deployment basis, just like in the tutorial for WildFly. As with when configuring WildFly, we do not need to import any additional JARs into WildFly, we can just package them with the application. NetBeans will actually do this for you, which makes this process even easier.
To keep things simple, let’s continue with the test application used in the previous blogs. For those fresh coming in, or for those who just want to start from scratch, here are the instructions:
  • Create a Server in NetBeans that maps to your Tomcat installation. 
  • Create a Java web application.
  • Create a Servlet in this new project.
  • Import the Log4j2 JARs to the project:
    • Right click on the project, and select properties
    • Go to the Librariespage
    • Select Add JAR/Folder, and import the following two files:
      • log4j-api-2.1.jar
      • log4j-core-2.1.jar
    • Click OK
  • Import the log4j package into your servlet by adding this code snippet below:
 import org.apache.logging.log4j.*;  
  • Declare and initialise a logger:
 private static Logger logger = LogManager.getLogger(TestServlet.class.getName());  
  • Add some logger messages at each log level to the processRequest method, so that they get executed when the Servlet is called:
 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter())
{
logger.trace("Tracing!");
logger.debug("Debugging!");
logger.info("Information!");
logger.warn("Warnings!");
logger.error("Oh noes!");
}
}
Having a try or finally block for our try clause would normally be expected, though to keep things basic we'll omit it (just don't make that excuse in your other code!).

  • Edit the index.htmlpage that was automatically generated when you created the project so that you can click on a button to call the servlet:
<html>
<head>
<title>Testing</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form name="testForm" action="TestServlet">
<input type="submit" value="push me!" name="testybutton" />
</form>
</body>
</html>
    With our test application created, let’s begin configuring Log4j2. As we are taking advantage of the Log4j configuration discovery process to find the configuration file on the classpath, the file must be called log4j2.xml. In NetBeans:
    • Expand the Web Pages folder of your test application in the project navigator pane.
    • Right click on the WEB-INF folder, and create a new folder inside it called classes.
    • Right click on this new classes folder, expand the Newmenu, and select XMLDocument.
    • Call it log4j2, and just create it as a well-formed document.
    • Fill it out as follows (replacing the fileName value with your own file path and file name):
    <?xml version="1.0" encoding="UTF-8"?>  
    <Configuration status="WARN">
    <Appenders>
    <File name="FileLogger" fileName="/home/andrew/tomcat.log">
    <PatternLayout pattern="%d{HH:mm} [%t] %-5level %logger{36} - %msg%n"/>
    </File>
    <Console name="ConsoleLogger" target="SYSTEM_OUT">
    <PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
    </Console>
    </Appenders>
    <Loggers>
    <Root level="trace">
    <AppenderRef ref="FileLogger"/>
    <AppenderRef ref="ConsoleLogger"/>
    </Root>
    </Loggers>
    </Configuration>
    This will log the messages we specified in the servlet to a custom file, and to the default Tomcat outlog, catalina.out. To help differentiate them, the messages logged to the console will log with the hour, minutes, and seconds, whereas the messages logged to our own file will only have the hour and minutes.

    Testing

    To test that everything is working as it should be, let’s give it a test run:
    • Clean and build the project, this will add the two JARs needed by the logger (log4j-api-2.1.jarand log4j-core-2.1.jar) to $project_install_location/build/web/WEB-INF/libdirectory, so that Tomcat can use them.
    • Right click on the project, and deploy it to Tomcat.
    • Click on the play button, and your browser should load with the application.
    • Click the button, and then check in your log file and in the catalina.out log file (this can be found in $tomcat_install_location/logs), you should see your logger messages.
      Take note: if you started Tomcat through NetBeans, then the log messages will not be output to the catalina.out file, instead being directed to the console output in NetBeans.

      Logback

      Fortuitously, Logback can be configured to work with Tomcat in almost exactly the same way as Log4j2, the only difference being the code syntax. I’ll go through the whole process again for those of you who are just jumping to this bit:
      • Create a Server in NetBeans that maps to your Tomcat installation.
      • Create a Java Web application.
      • Create a Servlet in this new project.
      • Import the Logback and SLF4J JARs into the project:
        • Right click on the project, and select properties
        • Go to the Librariespage
        • Select Add JAR/Folder, and import the following files:
          • slf4j-api-1.7.7.jar
          • logback-classic-1.1.2.jar
          • logback-core-1.1.2
        • Click OK
      • Import the following SLF4J packages into your servlet:
       import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      • Declare and initialise a logger:
       private static Logger logger = LoggerFactory.getLogger(TestServlet.class.getName());
      • Log some messages at various levels in the processRequest method, such that they get triggered when the Servlet is called:
       protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
      {
      response.setContentType("text/html;charset=UTF-8");
      try (PrintWriter out = response.getWriter())
      {
      logger.trace("Tracing!");
      logger.debug("Debugging!");
      logger.info("Information!");
      logger.warn("Warnings!");
      logger.error("Oh dears!");
      }
      }
      Again, we should really put a catch or finally block for the auto-generated try, but given that we're keeping this as basic as possible we'll omit it.

      As before, let’s edit the index.html page that was automatically generated for us so that you can click on a button to call the servlet:
      <html>
      <head>
      <title>Testing</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      </head>
      <body>
      <form name="testForm" action="TestServlet">
      <input type="submit" value="push me!" name="testybutton" />
      </form>
      </body>
      </html>
      Next, let’s create a logback configuration file that prints out our logger messages to a custom file, and to the catalina.out file. In NetBeans:
      • Expand the Web Pages folder of your test application in the project navigator pane.
      • Right click on the WEB-INF folder, and create a new folder inside it called classes.
      • Right click on this new folder, expand the New menu, and select XMLDocument.
      • Call it logback, and create it as a well-formed document; we don’t need any schema or DTD constraints for this.
      • Populate it with this (replacing /home/andrew/tomcat.log with your own file path and file name):
      <?xml version="1.0" encoding="UTF-8"?>  
      <configuration>
      <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
      <encoder>
      <pattern>%d{HH} [%thread] %-5level %logger{36} - %msg%n</pattern>
      </encoder>
      </appender>

      <appender name="FILE" class="ch.qos.logback.core.FileAppender">
      <file>/home/andrew/tomcat.log</file>
      <append>true</append>
      <encoder>
      <pattern>%d{HH:mm} [%thread] %-5level %logger{52} - %msg%n</pattern>
      </encoder>
      </appender>

      <root level="TRACE">
      <appender-ref ref="STDOUT"/>
      <appender-ref ref="FILE"/>
      </root>
      </configuration>
      Done! The only thing left to do is, build, deploy, and test the application.

      Testing

      Follow these instructions to build, deploy, and test the application:
      • Clean and build the project, this will add the JARs needed by the logger (logback-classic-1.1.2.jar, logback-core-1.1.2.jar, and slf4j-api-1.7.7.jar) to the $project_install_location/build/web/WEB-INF/libdirectory, so that they deploy to Tomcat with the application.
      • Right click on the project, and deploy it to Tomcat.
      • Click on the play button, and your browser should load with the application.
      • Click the button, and then check in the log file you specified in the Logback configuration, and in the catalina.out log file (this can be found in $tomcat_install_location/logs), you should see your logger messages.
      As I noted before, if you started Tomcat through NetBeans, then the log messages destined for the catalina.out file will instead be directed to the console output in NetBeans.

        Final Thoughts

        This is the last in this series, having covered GlassFish, WebLogic, WildFly, and now Tomcat; the “big four” Java EE application servers. I hope that you've found these tutorials helpful in getting started with using alternative logging frameworks with application servers, they do provide some benefits after all!

        Good luck from here!


          Viewing all articles
          Browse latest Browse all 223

          Trending Articles