I am struggling with Log4J and isDebugEnabled() method.
When I execute:
package org.test;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
public class Test {
public static Logger logger = Logger.getLogger(Test.class.getName());
public static void main(String[] args) { (new Test()).test(); }
public void test() {
System.out.println("Logger " + logger.getName());
System.out.println("level: " + logger.getLevel());
logger.setLevel(Level.DEB开发者_如何学GoUG);
System.out.println("level: " + logger.getLevel());
System.out.println("debug? " + logger.isDebugEnabled());
}
}
I get:
Logger org.test.Test
level: null
level: DEBUG
debug? false
The logger level is obviously DEBUG
, but logger.isDebugEnabled()
returns false.
Do you have an idea how to fix that?
EDIT:
I have tried with other versions of log4j and with a Level
cast, and it did not change anything.
I'd suggest you stop doing static Logger ....
. there is a very good article about the pros and cons which is well worth a read, epecially if you are on a server.
Another suggest I'd make would also be to look at Slf4j or LogBack if you can consider alternatives. Slf4j for example, doesn't require guard "if" statements around debug logging which in turn means cleaner code.
The reason seems to be a conflict with a dependency introduced through maven. I have tested to delete some of these dependencies, and it finally worked. I do not understand why, but... it works!
I tried to reproduce it with this code, but it works for me:
package com.example;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
public class LogTest {
public static Logger logger = Logger.getLogger(LogTest.class.getName());
public static void main(String[] args) {
System.out.println(logger.getLevel());
logger.setLevel(Level.DEBUG);
System.out.println(logger.getLevel());
System.out.println(logger.isDebugEnabled());
}
}
Output:
null
DEBUG
true
I've used log4j-1.2.15 for this test.
So maybe there's an issue with your version of log4j - switch to 1.2.14 or 1.2.15 for a moment and just check, if the problem is still there.
You should do the following (from JavaDoc):
logger.setLevel((Level) Level.DEBUG);
--
The only other difference I see between our examples is you have:
public static Logger logger = Logger.getLogger(Test.class.getName());
where I have:
public static Logger logger = Logger.getLogger(Test.class);
It's 99% probably not that, but as I said, that's the only difference.
精彩评论