开发者

Conventions regarding the loading of resource files to a Java project

Given that I'm having issues trying to apply an external log4j configuration via log4j.xml I'm now interested in adopting a convention regarding the loading of resource files to Java projects.

Despite the code works displaying the message without warnings or errors, I suspect the configuration is not being really applied as changing the ConversionPattern makes no difference to the console output.

Program.java

package the.project.path;

import java.io.File;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.PropertyConfigurator;

class Program {

  static final Logger logger = Logger.getLogger("SampleLogger");
  static final File config = new File("the.project.path/conf/log4j.xml");
  static final String message = "The quick brown fox jumps over the lazy dog.";

  public static void main(String[] args) {

    if (config.exists()) {
      PropertyConfigurator.configure(config.getPath());
    } else {
      BasicConfigurator.configure();
    }

    try {
      logger.debug(message);
      logger.info(message);
      logger.warn(message);
      logger.error(message);
      logger.fatal(message);

    } catch (Exception exception) {
      System.out.println(exception.toString());
    }
  }
}

log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  <appender name="SampleConsoleAppender" class="org.apache.log4j.ConsoleAppender"> 
    <layout class="org.apache.log4j.PatternLayout">
    <!--  
    TTC开发者_如何学GoC is a message format used by log4j.
    TTCC is acronym for Time Thread Category Component.
    It uses the following pattern: %r [%t] %-5p %c %x - %m%n
    -->
    <param name="ConversionPattern" value="[%t] [%-5p] - %m%n" />
    </layout>
  </appender>
  <root>
  <appender-ref ref="SampleConsoleAppender" />
  </root>
</log4j:configuration>

Any advice will be really appreciated. Thanks much in advance.


Try using the DOMConfigurator, thus:

// Load log4j config file...
String path = "/path/to/log4j.xml");
DOMConfigurator.configure(path);

// Start Logging
LOG = Logger.getLogger(Program.class);

(code ripped from my current project, so I know it works) ;-)

As well as the above use of DOMConfigurator, you can optionally set a watch period, whereby Log4J will poll the xml file for changes, every xx millis, and then reload the changes:

// Load log4j config file...
String path = "/path/to/log4j.xml");
DOMConfigurator.configureAndWatch(path, 30000); // 30sec poll

// Start Logging
LOG = Logger.getLogger(Program.class);

HTH


You can try setting -Dlog4j.debug=true to see which options are being applied to log4j. It doesn't answer your resource loading question, but it is helpful to know that usually.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜