Thursday, September 22, 2005

[Tips] Wanted to use Log4j with Sun Java System App Server 8?

I prefer log4j over JDK 1.4 logging library, hera are some of the "obvious" reasons: How about log4j comes with more appenders compare to JDK1.4 Logging, it easier to configure, and support many layouts. However, log4j does not “sits” very well in our App Server, some of identified problems are:
1.Deployed logging configuration file (i.e. log4j.properties) is totally ignore, even we put in correct class path.
2.Logger ClassCast Exception upon restart of an application server instance.

A further investigate reveal that our Apps Server use JDK1.4 logging (i.e. Java.util.logging) via apache commons-logging, which should be avoided according to this article http://www.qos.ch/logging/thinkAgain.jsp, I agree. So, here's propose “work around”:
1.Write you own log4j wrapper class. Refer to “Ch9, Log4j, the complete manual” by log4j author Ceki Gülcü for more information on how to write a good log4j logger wrapper class.

2.Create a new Logger Manager, which will a)Configure log4j properties if is not configured yet b)Return the logger wrapper class to calling class. As an example of such Logger Manager class:
   1:
2:public class MyLogManager {
3: private static boolean isLogPropertiesConfigure = false;
4:
5:
6: public MyLogManager() {
7: }
8:
9:
10: public static MyLog4JWrapper getInstance(String logInstance) {
11: try {
12: if (!isLogPropertiesConfigure) {
13: PropertiesConfiguration pp = new PropertiesConfiguration(Constants.PRJ_PROPERTIES_FILE);
14: String configFile = pp.getString(
15: "log4j.properties.file");
16: FileInputStream istream = new FileInputStream(configFile);
17:
18: Properties props = new Properties();
19: props.load(istream);
20: istream.close();
21: PropertyConfigurator.configure(props);
22: isLogPropertiesConfigure = true;
23: }
24: } catch (Exception e) {
25: System.out.println("Error :" + e.toString());
26: }
27:
28: return new MyLog4JWrapper(logInstance);
29: }
30:}
3. Finally, use LoggerManager, and MyLogJWrapper for logging in your J2EE applications, example:
   1:public class MyClass{
2: static MyLog4jWrapper log= MyLoggerManager.get(MyClass.class.getName());
3:
4:
5:
6: public void someMethod() {
7: log.debug("Testing...");
8: }
9:}

No comments: