Here’s another way How to use log4j.xml example in application. In this example you will see how we use xml logging.How to use log4j.xml example

1. Output to Console

Redirect the logging to console.

log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
  xmlns:log4j='http://jakarta.apache.org/log4j/'>

  <appender name="console" class="org.apache.log4j.ConsoleAppender">
      <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern"
      value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
      </layout>
  </appender>

  <root>
    <level value="DEBUG" />
    <appender-ref ref="console" />
  </root>

</log4j:configuration>

2. Output to File

Redirect the logging to a file..

log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
  xmlns:log4j='http://jakarta.apache.org/log4j/'>

  <appender name="file" class="org.apache.log4j.RollingFileAppender">
     <param name="append" value="false" />
     <param name="maxFileSize" value="10KB" />
     <param name="maxBackupIndex" value="5" />
     <!-- For Tomcat -->
     <param name="file" value="${catalina.home}/logs/myStruts1App.log" />
     <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern"
      value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
     </layout>
  </appender>

  <root>
    <level value="ERROR" />
    <appender-ref ref="file" />
  </root>

</log4j:configuration>

An example of log4j rolling files.

log4j-file-location
 

3. Output to Console and File

Full example to output the logging to both console and file.

log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
  xmlns:log4j='http://jakarta.apache.org/log4j/'>

  <appender name="console" class="org.apache.log4j.ConsoleAppender">
      <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern"
      value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
      </layout>
  </appender>

  <appender name="file" class="org.apache.log4j.RollingFileAppender">
      <param name="append" value="false" />
      <param name="maxFileSize" value="10MB" />
      <param name="maxBackupIndex" value="10" />
      <param name="file" value="${catalina.home}/logs/myStruts1App.log" />
      <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern"
      value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
      </layout>
  </appender>

  <root>
    <level value="DEBUG" />
    <appender-ref ref="console" />
    <appender-ref ref="file" />
  </root>

</log4j:configuration>
Reference : mkyong

Leave a Reply

Your email address will not be published. Required fields are marked *