I am using an SDK that uses Apache CXF internally. Apache CXF uses the java.util.logging
package for logging by default.
I want to change the logging level from INFO
to WARNING
or turn it off completely. Can I do this programmatically in the main method of my application?
To disable this behavior, you must add a logback configuration file called logback. xml in your java classpath root. You can download this minimal logback. xml file and add it in the src/main/resources directory for a maven project or beside fr directory for a simple java project.
Logging in simple words refers to the recording of an application activity. Logging is used to store exceptions, information, and warnings as messages that occur during the execution of a program. Logging helps a programmer in the debugging process of a program. Java provides logging facility in the java. util.
There is a way to do this programatically, but it's not intuitive. Changing to SLF4J or Log4J may be better if you end up needing control at a a finer level or over multiple classes
The issue is that Loggers are cached using WeakReferences. From the time you call Logger.setLevel()
until the Logger is actually used, it may be GC'ed. So, the Logger that logs isn't the Logger you set the level on! This is especially true in frameworks where there is a lot of GC at startup.
The solution is to programatically set the configuration, not the actual Loggers.
String logConfig = ".level=" + java.util.logging.Level.INFO + '\n';
logConfig += "handlers=java.util.logging.ConsoleHandler\n";
// ensure ConsoleHandler does not filter
logConfig += "java.util.logging.ConsoleHandler" + ".level=" + java.util.logging.Level.FINEST + '\n';
//set your custom levels
logConfig += "org.apache.cxf" + ".level=" + java.util.logging.Level.WARNING + "\n";
try {
java.util.logging.LogManager.getLogManager().readConfiguration(new java.io.ByteArrayInputStream(logConfig.getBytes("UTF-8")));
// no need to close ByteArrayInputStream -- it is a no-op
}
catch (IOException ioe) {
System.err.println("cannot fully configure logging");
ioe.printStackTrace();
}
Note there are a few issues with this approach:
-Djava.util.logging.config.file
, it will also be overwritten.\n
.main()
. If this is not possible, you may also need to iterate all the existing Loggers and update their config using setLevel()
too.The link below from Apache CXF has a well understood documentation whether it's java.util.logging or log4j or sl4j:
http://cxf.apache.org/docs/general-cxf-logging.html
It would be very easy if you are using log4j.
You can configure log4j for Apache CXF and then append something like as follows in log4j.properties file which will turn off apache cxf logging.
log4j.apache.cxf = WARN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With