How to have multiple loggers with shared code also using the logger?
In ${catalina.home}/lib there is a jar file that contains class MyLog. There
is a function in it
public class MyLog
{
public static Logger getLogger()
{
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL log4j_properties = classLoader.getResource("log4j.properties");
String loggerName = log4j_properties != null ?
log4j_properties.toString() : "default";
synchronized (MyLog.class)
{
Logger logger =
Logger.getRootLogger().getLoggerRepository().exists(loggerName);
if (logger == null)
{
logger = Logger.getLogger(loggerName);
System.out.println("Created logger: loggerName=" + loggerName);
}
return logger;
}
}
}
The jar file in ${catalina.home}/lib contains common code used by all web
applications, and it calls MyLog.getLogger() to write some logs.
My ROOT application in ${catalina.home}/webapps/ROOT and web service
application in ${catalina.home}/webapps/mywebservice also call MyLog.
The intent of getLogger() above is to return the logger for the application
currently being run. I have verified that
Thread.currentThread().getContextClassLoader().hashCode() has value1 for the
ROOT application and value2 for the mywebservice application.
We have the following two log4j.properties:
${catalina.home}/webapps/ROOT/WEB-INF/lib/root.jar!/log4j.properties
${catalina.home}/webapps/mywebservice/WEB-INF/lib/root.jar!/log4j.properties
The value of loggerName is the first one when we're running the ROOT
application, and the second one when running the mywebservice application. So
far, so good.
After starting Tomcat, if we run the ROOT application first, then it will call
MyLog.getLogger(), and the log4j.properties found by the call to
Logger.getLogger() will be the first one above. If we run mywebservice first,
then Logger.getLogger() will find the second log4j.properties file. Any
subsequent call to Logger.getLogger() will use the same log4j.properties. So
suppose we run the ROOT application first, then the new logger will be
initialized with the first log4j.properties above. And then if mywebservice
calls MyLog.getLogger(), a new logger will get created, but it will be based on
the same log4j.properties file. You can see this because all applications log
to the same file (each of my log4j.properties specifies a different file).
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]