Reputation: 29
We are making a program that consists of several embbeded jars. Each jar requires an individual log file. The problem is that when we are trying to log in the core jar file, the log messages are written in the log files of the other jars.
This is the code of the core jar file.
static Logger logCore = LogManager.getLogger(); //log file created
public static void main(String[] args)
{
LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
org.apache.logging.log4j.core.selector.BasicContextSelector
File file = new File("/home/pi/NetBeansProjects/CoreService/dist/log4j2.xml");
context.setConfigLocation(file.toURI());
logCore.info("Core Service initiated"); //Log here is done in the lof od the Core jar as expected
//Run methods of another jar (DBcontrollers)
try
{
SmartBoxSN = DBControllers.DeviceSetupController.GetOwnDeviceSetupFieldNameID(3).Value;
}
catch(SQLException | ClassNotFoundException ex)
{
}
logCore.info("Core Service initiated"); //Log here is wrongly done in the log file of DBControllers
}
How can we select the log file in which we want to log?
Upvotes: 0
Views: 1371
Reputation: 159096
All your jars are loaded by a single ClassLoader, so there is only one instance of Log4j, and therefore only one configuration.
Presumably, each jar file has classes from different packages, and you can send log messages to different appenders depending on the logger name, i.e. the name of the class generating the log message.
So, define multiple appenders, and then configure the loggers with additivity="false"
and specify the appender to use, for each base package.
Example: If you have core.jar
with classes from package com.example.core
and subpackages, and extension.jar
with classes from package com.example.ext
and subpackages, you'd use a configuration like this:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<File name="MainFile" fileName="main.log">
. . .
</File>
<File name="CoreFile" fileName="core.log">
. . .
</File>
<File name="ExtFile" fileName="ext.log">
. . .
</File>
</Appenders>
<Loggers>
<Logger name="com.example.core" level="info" additivity="false">
<AppenderRef ref="CoreFile"/>
</Logger>
<Logger name="com.example.ext" level="info" additivity="false">
<AppenderRef ref="ExtFile"/>
</Logger>
<Root level="info">
<AppenderRef ref="MainFile"/>
</Root>
</Loggers>
</Configuration>
Upvotes: 3