Configuring with BasicConfigurator.configure();
sets up a basic console appender set at debug. A project with the setup above and no other code (except for a test) should produce three lines of logging in the console. I cannot say anything else than "it works for me".
Have you tried creating an empty project with just log4j and junit, with only the code above and ran it?
Also, in order to get the @Before
method running:
@Test
public void testname() throws Exception {
assertTrue(true);
}
EDIT:
If you run more than one test at one time, each of them will call init before running.
In this case, if you had two tests, the first would have one logger and the second test would call init again, making it log twice (try it) - you should get 9 lines of logging in console with two tests.
You might want to use a static init method annotated with @BeforeClass
to avoid this. Though this also happens across files, you might want to have a look at documentation on TestSuites in JUnit 4. And/or call BasicConfigurator.resetConfiguration();
in an @AfterClass annotated class, to remove all loggers after each test class / test suite.
Also, the root logger is reused, so that if you set the root logger's level in a test method that runs early, it will keep this setting for all other tests that are run later, even if they are in different files. (will not happen when resetting configuration).
Testcase - this will cause 9 lines of logging:
import static org.junit.Assert.assertTrue;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
public class SampleTest
{
private static final Logger LOGGER = Logger.getLogger(SampleTest.class);
@Before
public void init() throws Exception
{
// Log4J junit configuration.
BasicConfigurator.configure();
}
@Test
public void testOne() throws Exception {
LOGGER.info("INFO TEST");
LOGGER.debug("DEBUG TEST");
LOGGER.error("ERROR TEST");
assertTrue(true);
}
@Test
public void testTwo() throws Exception {
LOGGER.info("INFO TEST");
LOGGER.debug("DEBUG TEST");
LOGGER.error("ERROR TEST");
assertTrue(true);
}
}
Changing the init method reduces to the excepted six lines:
@BeforeClass
public static void init() throws Exception
{
// Log4J junit configuration.
BasicConfigurator.configure();
}
Your problem is probably caused in some other test class or test suite where the logging level of the root logger is set to ERROR, and not reset.
You could also test this out by resetting in the @BeforeClass method, before setting logging up.
Be advised that these changes might break expected logging for other test cases until it is fixed at all places. I suggest trying out how this works in a separate workspace/project to get a feel for how it works.