mercoledì 6 febbraio 2013

Enabling and using log4j on JBoss AS 7

Hi all,
today we will see how to enable and use log4j on JBoss as 7.
As you may already know JBoss comes already with his own version of log4j which is located under %jboss-home/modules/org/apache/log4j.


The following steps explains you what you have to do:
  1.  add the log4j.jar to your classpath, this may be done easly with the following steps
    • right click on your application - ejbmodule, Build path , configure build path..
    • then Add external jar, which you will find in the path mentioned above 
  2. Configure the logger. See below.
  3. Go the class you want to use the logger, suppose is in "mypackage.subpackage"
    add the import at the top of the class
    import org.apache.log4j.Logger;
  4.  create a field with the logger:
    private static Logger logger = Logger.getLogger(YourEJBClass.class);
  5. use the logger
    logger.info("started"); logger.debug("value of x" + x.toString());


Configure the logger

JBoss already comes with a configuration file under %Jboss-home/standalone/configuration/standalone.xml.
By default, your logger will output to server.log and console, but you can add some appender to output your app logs to another file.
Stop the server before start modifing the standalone.xml.
Log4j is highly customizable, here is a basic configuration:

<periodic-rotating-file-handler name="FILETWO">
  <formatter>
    <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
  </formatter>
  <file relative-to="jboss.server.log.dir" path="mylogfile.log"/>
  <suffix value=".yyyy-MM-dd"/>
  <append value="true"/>
</periodic-rotating-file-handler>
This will be added in the standalone.xml, you can put it in the subsystem forlogging, after the CONSOLE one and the FILE one.

After this snippet of code, and before the <root-logger> node you can put the following snippet
<logger category="mypackage.subpackage">
    <level name="DEBUG"/>
    <handlers>
        <handler name="CONSOLE"/>
        <handler name="FILETWO"/>
    </handlers>
</logger>
Start again the server and enjoy your logging system.


sources: my original question at stackoverflow. Rafael answers and his blog