[java] Log4j output not displayed in Eclipse console

For some reason my Eclipse console no longer displays Log4j INFO and DEBUG statements when I run JUnit tests. In terms of code there hasn't been any change, so it must something to do with the Eclipse configuration.

All I do in my Unit test is the following and for some reason ONLY the ERROR statement is displayed in the Eclipse console. Why? Where shall I look for clues?

public class SampleTest
{
   private static final Logger LOGGER = Logger.getLogger(SampleTest.class);

   @Before
   public void init() throws Exception
   {
       // Log4J junit configuration.
       BasicConfigurator.configure();

       LOGGER.info("INFO TEST");
       LOGGER.debug("DEBUG TEST");
       LOGGER.error("ERROR TEST");
   }
}

Details:

  • log4j-1.2.6.jar
  • junit-4.6.jar Eclipse
  • IDE for Java Developers, Version: Helios Release, Build id: 20100617-1415

This question is related to java eclipse junit log4j

The answer is


Thought this was a genuine defect but it turns out that my console size was limited, and caused the old content past 80000 characters to be cut off.

Right click on the console for the preferences and increase the console size limit.


There is a case I make: exception happen in somewhere, but I catched the exception without print anything, thus the code didn't even reach the log4j code, so no output.


Add a test dependency to your pom to slf4j.

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>${slf4j.version}</version>
            <scope>test</scope>
        </dependency>

if the log4j.xml file is not in the project,and you are using tomcat, try going to tomcat instance and search for log4j. Try changing the consoleAppender level to debug and redeploy the application in tomcat. That might help.


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 @Beforemethod 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.


Sounds like log4j picks up another configuration file than the one you think it does.

Put a breakpoint in log4j where the file is opened and have a look at the files getAbsolutePath().


Check your log4j.properties file

Check easy example here at here.


Check that your log4j.properties or log4j.xml are copied to your IDE classpath and loads when calling BasicConfigurator.configure()


I had the same error.

I am using Jboss 7.1 AS. In the configuration file - standalone.xml edit the following tag. (stop your server and edit)

     <root-logger>
            <level name="ALL"/>
            <handlers>
                <handler name="CONSOLE"/>
                <handler name="FILE"/>
            </handlers>
    </root-logger>

The ALL has the lowest possible rank and is intended to turn on all logging.


Look in the log4j.properties or log4j.xml file for the log level. It's probably set to ERROR instead of DEBUG


I once had an issue like this, when i downloadad a lib from Amazon (for Amazon webservices) and that jar file contained a log4j.properties and somehow that was used instead of my good old, self configed log4j. Worth a check.


The Eclipse Console Window has a Filter Property (in some cases only system.err is active).

Rigt click into Eclipse console window -> Preferences -> Console and ensure that checkbox

Show when Program writes to standard out

is active.

Alternatively you can configure log4j to write alway to System.err like this:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="AppConsole" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.err" />
        <param name="Encoding" value="ISO-8859-15" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{dd.MM.yyyy HH:mm:ss} %5p kontext.%c{1}:%L - %m%n" />
        </layout>
    </appender>
    <root>
        <level value="debug" />
        <appender-ref ref="AppConsole" />
    </root>
</log4j:configuration> 

Makes sure when running junit test cases, you have the log4j.properties or log4j.xml file in your test/resources folder.


A simple log4j.properties file can look like this:

log4j.rootCategory=debug,console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.out
log4j.appender.console.immediateFlush=true
log4j.appender.console.encoding=UTF-8
log4j.appender.console.threshold=info

log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d [%t] %-5p %c - %m%n

Place it in your class path (target/classes folder). Or you if you have a Maven project, place it under your src/main/resources and Eclipse will copy it to your class path.

Without a configuration file, you should see an Eclipse warning in the console like this:

log4j:WARN No appenders could be found for logger.
log4j:WARN Please initialize the log4j system properly.

My situation was solved by specifing the VM argument to the JAVA program being debugged, I assume you can also set this in `eclipse.ini file aswell:

enable-debug-level-in-eclipse


One thing to note, if you have a log4j.properties file on your classpath you do not need to call BasicConfigurator. A description of how to configure the properties file is here.

You could pinpoint whether your IDE is causing the issue by trying to run this class from the command line with log4j.jar and log4j.properties on your classpath.


Go to Run configurations in your eclipse then -VM arguments add this: -Dlog4j.configuration=log4j-config_folder/log4j.xml

replace log4j-config_folder with your folder structure where you have your log4j.xml file


Check for log4j configuration files in your output (i.e. bin or target/classes) directory or within generated project artifacts (.jar/.war/.ear). If this is on your classpath it gets picked up by log4j.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to eclipse

How do I get the command-line for an Eclipse run configuration? My eclipse won't open, i download the bundle pack it keeps saying error log strange error in my Animation Drawable How to uninstall Eclipse? How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Class has been compiled by a more recent version of the Java Environment Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9 "The POM for ... is missing, no dependency information available" even though it exists in Maven Repository The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

Examples related to junit

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory How to resolve Unneccessary Stubbing exception JUnit 5: How to assert an exception is thrown? How do I mock a REST template exchange? Class Not Found: Empty Test Suite in IntelliJ Unable to find a @SpringBootConfiguration when doing a JpaTest Failed to load ApplicationContext (with annotation) Example of Mockito's argumentCaptor Mockito - NullpointerException when stubbing Method Spring jUnit Testing properties file

Examples related to log4j

No log4j2 configuration file found. Using default configuration: logging only errors to the console How to stop INFO messages displaying on spark console? What is log4j's default log file dumping path How to give environmental variable path for file appender in configuration file in log4j No appenders could be found for logger(log4j)? SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project log4j:WARN No appenders could be found for logger (running jar file, not web app) Error: "setFile(null,false) call failed" when using log4j java.lang.ClassNotFoundException: org.apache.log4j.Level How can I create 2 separate log files with one log4j config file?