Search code examples
javalogginglog4jclasscastexceptionesapi

ClassCastException: org.apache.log4j.Logger cannot be cast to org.owasp.esapi.Logger


As seen from the title I am getting a class cast exception when trying to replace my log4j/slf4j logging with ESAPI logging in my code. Specifically, it happens in the following method:

    private Logger log()
    {
        return ESAPI.getLogger(getClass());
    }

The following are the imports specific to the logger:

    import org.owasp.esapi.ESAPI;
    import org.owasp.esapi.Logger;

What makes this mind boggling to me is that there is ESAPI logging in place in other classes which works just fine. From my understanding, I thought if log4j loggers were in place and working then that it would be a simple matter of swapping it out for ESAPI since it's an extension of it. My log4j properties file also has the loggerFactory defined --

    log4j.loggerFactory=org.owasp.esapi.reference.Log4JLoggerFactory

Any ideas as to what might be going on? This is just a simple java/struts/spring app.


Solution

  • Even though you are using the ESAPI Log4jLoggerFactory and under the hood, that uses the log4j Logger, that does not mean that org.owasp.esapi.Logger ISA org.apache.log4j.Logger. Not even related for that matter. ESAPI's logger was not done that way because it was also designed to support java.util.logging.Logger. As a result of that design decision, org.owasp.esapi.Logger is an interface and thus you cannot cast it to anything. (That is, it extends neither org.apache.log4j.Logger or java.util.logging.Logger. Rather the implementation is more done as a wrapper.)

    Of course, that doesn't solve your problem. If you really wanted to use it, you'd have to write a fair portion of code to extend ESAPI's logger and make the underlying implementation class available, which somewhat defeats the point of information hiding.

    That said, I'm not defending the design decision. It is what it is and those crucial design decisions were made well before I got involved in the project.

    -kevin