Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Alternative Logging Frameworks for Application Servers: WildFly

DZone's Guide to

Alternative Logging Frameworks for Application Servers: WildFly

· Integration Zone
Free Resource

Today’s data climate is fast-paced and it’s not slowing down. Here’s why your current integration solution is not enough. Brought to you in partnership with Liaison Technologies.

Introduction

Welcome to the third part of our blog series on configuring application servers to use alternative logging frameworks. This time we turn our gaze to WildFly, the open source application server from JBoss. Again, we'll be configuring it to use Log4j2 and SLF4J with Logback.

For those of you who are looking for parts 1 and 2 of this series, find them here:
Part 1 - GlassFish
Part 2 - WebLogic

For reference, the environment used for this blog was: a 64-bit Linux VM, JDK 8u20, Log4j 2.0.2, Logback 1.1.2, SLF4J 1.7.7, WildFly 8.1, and building/programming done using NetBeans 8.0.

As with the previous entries in this series, I'll be assuming you have set up WildFly before attempting to follow this blog. For a simple guide on this, check out Jboss' one on clustering; it's pretty easy to follow and will get you set up with a basic environment if you don't have one already.

Following the norm of this series, let's begin with Log4j2.

Log4j2

Log4J2 is pretty easy to set up with WildFly on a per deployment basis; WildFly does not officially support using your own loggers on a domain wide basis, meaning that the configuration detailed in this blog will only apply to this application in particular (just as with when using SLF4J and Logback with WebLogic as described in my previous blog).

As we are configuring this on a "per deployment" basis (or per application if you prefer), we do not need to import any jars into WildFly; we package them with the application. With this in mind, let's create a test application (if you've read the previous two blogs in this series, you'll recognise the program):

  • Create a Server in NetBeans that maps to your WildFly installation (you'll need the WildFly plugin: tools, plugins, Available Plugins, WildFly Application Server)
  • Create a Java Web application
  • Create a Servlet in this project.
  • Download Log4j and add the following two JARs into the project:
    • log4j-api-2.0.2.jar
    • log4j-core-2.0.2.jar
  •  Add the following import statement into your servlet:
import org.apache.logging.log4j.*; 
  •  Declare and initialise the logger:
 private static Logger logger = LogManager.getLogger(TestServlet.class.getName());
  •  Edit the processRequest method to this:
 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!");  
      }  
 }
 With the log messages done, edit the index.html page that NetBeans created for you to provide a button for us to call the servlet with:
<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 the programming done, we need to create a configuration file for Log4j to use. Shaking it up a little from the previous blogs in the series, we'll create a configuration file, log4j2.xml, that prints log messages of any level to a file in my home directory (replace the /home/andrew directory with wherever you want the log file to be stored):

  • In the WEB-INF folder of your NetBeans project, create a folder called classes
  • Create an xml file in here named log4j2.xml, and populate it with this: 
 <?xml version="1.0" encoding="UTF-8"?>  
 <Configuration status="WARN">  
    <Appenders>  
       <File name="FileLogger" fileName="/home/andrew/wildfly.log">  
          <PatternLayout pattern="%d{HH:mm} [%t] %-5level %logger{36} - %msg%n"/>  
       </Console>  
    </Appenders>  
    <Loggers>  
       <Root level="trace">  
          <AppenderRef ref="FileLogger"/>  
       </Root>  
    </Loggers>  
 </Configuration> 
Done! Build your application and deploy it to WildFly. Open the application in your browser, click on the button, and you should find a file created in your home directory with your log messages in.

SLF4J and Logback

Just as before, to use our own SLF4J and Logback binding and configuration, we'll configure for a per deployment basis. First things first, let's get our application to use Logback:

  • Download SLF4J and Logback, and add the following JARs to your web application:
    • slf4j-api
    • logback-core
    • logback-classic
  •  Remove the Log4j package and instead import:
import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
  •  Alter the logger initialisation to:
 private static Logger logger = LoggerFactory.getLogger(TestServlet.class.getName());
The processRequest method does not require any additional changes on top of how we've already changed it, though feel free to alter the messages for fun; I changed the error level message to "oh dears" for clarity since my configuration had both applications writing to the same file (and if you're following this blog, so soon shall yours).

Create an xml file in the WEB-INF/classes directory called logback.xml, and fill it with this configuration (it performs the same function as the Log4j2 one):
 <configuration>  
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">  
       <file>/home/andrew/wildfly.log</file>  
       <append>true</append>  
       <encoder>  
          <Pattern>%d{HH:mm} [%thread] %-5level %logger{52} - %msg%n</Pattern>  
       </encoder>  
    </appender>  
    <root>  
       <level value="TRACE"/>  
       <appender-ref ref="FILE"/>  
    </root>  
 </configuration> 
Unlike configuring WildFly with Log4j2 however, we are not yet done. We need to disable the add-logging-api-dependencies setting to stop WildFly from adding its implicit logging dependencies to our deployment. To do this, we need to use the JBoss CLI.

Navigate to the bin directory of WildFly, and run the following command (replacing $ip and $port with your own specific values):
 jboss-cli.sh -c controller=$ip:$port --gui

This will bring up a window, through which you can modify global WildFly settings. If youhadn't realised, WildFly will need to be running for you to run this command successfully. The setting we are after is in the logging subsystem. If you're in domain mode (like the guide I linked to at the top leads you to be in), you'll need to make the changes to the server group that you're deploying the application to.

Right click on the add-logging-api-dependencies setting, select write-attribute, and untick the value box. The cmd box at the top may catch your eye when you click OK as it fills with a command; this is the command that you would have to fill in if you were using the command line. Click submit in the top right hand corner, and the output should display "success".

Restart WildFly and lo! You're ready to deploy!

Wrapping Up

You should now have a grounding in how to use alternative logging with WildFly, affording you more logging flexibility in your work and endeavours.The final entry in this series will cover Apache Tomcat, so check back for it soon. In the meantime, read some of our other blogs on WildFly and JBoss Server:

WildFly 8.0.0.Final is Released
Securing JBoss EAP 6 - Implementing SSL
How to controll *all* JTA properties in JBoss AS 7 / EAP 6







Is iPaaS solving the right problems? Not knowing the fundamental difference between iPaaS and iPaaS+ could cost you down the road. Brought to you in partnership with Liaison Technologies.

Topics:

Published at DZone with permission of Andrew Pielage. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}