Powermock : MockClassLoader Issue with Log4j

When running a PowerMock Test Log4j gives me the following (or something similar) error:-

log4j:ERROR A "org.apache.log4j.xml.DOMConfigurator" object is not assignable to a "org.apache.log4j.spi.Configurator" variable.
log4j:ERROR The class "org.apache.log4j.spi.Configurator" was loaded by
log4j:ERROR [org.powermock.core.classloader.MockClassLoader@14a55f2] whereas object of type
log4j:ERROR "org.apache.log4j.xml.DOMConfigurator" was loaded by [sun.misc.Launcher$AppClassLoader@92e78c].
log4j:ERROR Could not instantiate configurator [org.apache.log4j.xml.DOMConfigurator].


Caused by: org.apache.commons.logging.LogConfigurationException:Invalid class loader hierarchy.  
You have more than one version of 'org.apache.commons.logging.Log' visible, which is not allowed.

There are a couple of different solutions to this:
# Upgrade to PowerMock 1.3+
# Make use of the @PowerMockIgnore annotation at the class-level of the test.
For example if using log4j, use `@PowerMockIgnore(“org.apache.log4j.*”)` if using commons logging, use `@PowerMockIgnore(“org.apache.commons.logging.*”)`.

Reference URL :-


How to set variable which could be used as a configuration for log4j?

Following are the steps which could be used as a configuration for log4j:-

(1) In log4j.xml define variable as ${variable}:

<appender name="FILE" class="org.apache.log4j.FileAppender">    
    <param name="File" value="${logfilename}.log" />
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d::[%t]::%-5p::%c::%x - %m%n" />

(2) Then make sure you set the system property when you start your JVM such as:
java -Dlogfilename=VinayFileLogger com.vinay.myApplication

(3) Alternatively, you can set the system property in code so long as you do it before you create a logger (this is useful if you want your PID in your logs for instance). Such as:
System.setProperty(“logfilename”, ” VinayFileLogger “);

(4) Once that is set you can go ahead and get your loggers as normal and they will log to the dynamic file

How to set VM arguments in Tomcat
(1) Right Mouse Click on Tomcat Server >> Configure Server Connector
(2) Select Preference >> Tomcat >> Tomcat x.x >> JDK
(3) Now, set the VM arguments as per the snapshot.