I'm using java logging to write log messages of my application to a log file and other destinations. Having set the log level to FINE, I also get (unwanted) messages from AWT/Swing, such as:
{0}, when grabbed {1}, contains {2}
and others. Looking at the JDK source code (see e.g. here), one sees that the name of the corresponding logger is sun.awt.X11.grab.XWindowPeer.
What I understood from the Java logging framework is that this logging handler should inherit its loglevel from its parents like sun.awt.
I tried the following:
Logger.getLogger("sun.awt").setLevel(Level.OFF);
but the AWT/Swing debug messages still appear in the log output.
What's the recommended way of programmatically disabling these log messages (while still allowing FINE messages from other sources) ?
If you just want to log the messages of your own application, you can disable all messages and then explicitly enable messages for your application:
Logger.getRootLogger().setLevel(Level.OFF);
Logger.getLogger("package.of.your.application").setLevel(Level.ALL);
Inside the properties-file for logging (e.g. logging.properties) this would be:
.level = OFF
package.of.your.application.level = ALL
I had the same problem today. Searching on google this is the top url and I don't find a good source to a answer, so I will post mine :)
Assuming that Andre use the java.util.logging API, it's possible to add a Handler that will control the format of your log, using setFormatter(Formatter newFormatter).
So I extended Formatter and checked if the class of the log contains java.awt, javax.swing or sun.awt.
class MyFormatLog extends Formatter {
#Override
public String format(LogRecord record) {
if( !record.getSourceClassName().contains("java.awt") &&
!record.getSourceClassName().contains("javax.swing.") &&
!record.getSourceClassName().contains("sun.awt.") ) {
//format my output...
} else {
return "";
}
}
}
I could not find the getRootLogger() method in the Logger class any more. This is what works for me:
logger = Logger.getLogger("my.package");
Logger l = logger;
while (l != null) {
l.setLevel(Level.OFF);
l = l.getParent();
}
logger.setLevel(Level.FINER);
Logger.getLogger("java.awt").setLevel(Level.OFF);
Logger.getLogger("sun.awt").setLevel(Level.OFF);
Logger.getLogger("javax.swing").setLevel(Level.OFF);
Try
Logger.getRootLogger().setLevel(Level.OFF);
Related
I've got a simple setup to log a message: JDK 8 Update 65 and Eclipse Mars
import java.util.logging.Logger;
public class Example {
private final static Logger LOGGER = Logger.getLogger(Example.class.getName());
public static void main(String[] args) {
LOGGER.info("Test");
}
}
I would expect to get an output on the stdout, just like using System.out.println();.
But instead it gets printed out on the stderr, which results in a red font on the eclipse console:
I know that I can change this behavior by writing a custom Handler, but I wish to know why the default output appears on the stderr instead of stdout?
A logger should use stdout for fine+info and use stderr for severe level.
The java.util.logging API was developed under JSR 47: Logging API Specification. According to the change log in the "Proposed Final Draft" the ConsoleHandler always used System.err. The JCP page also lists the original authors of the API and I think only those names truly know the answer to your question.
That said, I think the origin comes from System.err API docs.
Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out, has been redirected to a file or other destination that is typically not continuously monitored.
Opposed to System.out:
The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.
Logging maps to diagnostics and not raw data. It is important to separate data from diagnostic error information especially when piping processes together as the downstream consumers are only ready to accept data information and not error messages. See Confused about stdin, stdout and stderr? for more detailed information.
It is well documented. By default, loggers publish to their parent's handlers, recursively up to the tree, until the other handler has been specified. You can loop over the parent's handlers and see that the default handler of the parent's logger is ConsoleHandler which uses System.err to publish log records.
public class Main {
public static void main(String[] args) {
Handler[] handlers = Logger.getLogger(Main.class.getName()).getParent().getHandlers();
for (Handler handler : handlers) {
System.out.println(handler.getClass().getName());
}
}
}
You can create and extended ConsoleHandler to set the out to System.out instead of System.err
Logger logger = Logger.getLoger("your_logger_name");
logger.setUseParentHandler(false);
logger.addHandler(new ConsoleHandler() {
{setOutputStream(System.out);}
});
Now all message on this logger will appear in the System.out console.
By default, the logger outputs log records of level INFO and above (i.e., INFO, WARNING and SEVERE) to standard error stream (System.err).
Source: www3.ntu.edu.sg/home/ehchua/programming/java/JavaLogging.html
the reason they use stderr is because this stream "is used for error messages and diagnostics issued by the program" (source: https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html).
I am trying to use LoggerHandler to log all incoming requests. I am using logback.xml to specify appenders. I am setting system property for logging.
System.setProperty("org.vertx.logger-delegate-factory-class-name",
"org.vertx.java.core.logging.impl.SLF4JLogDelegateFactory");
Still it is logging everything in console not in file.
This worked for me with Vert.x 3.4.1:
import static io.vertx.core.logging.LoggerFactory.LOGGER_DELEGATE_FACTORY_CLASS_NAME;
import io.vertx.core.logging.LoggerFactory;
// ...
setProperty (LOGGER_DELEGATE_FACTORY_CLASS_NAME, SLF4JLogDelegateFactory.class.getName ());
LoggerFactory.getLogger (LoggerFactory.class); // Required for Logback to work in Vertx
The key is to get a logger, which I guess initializes the Logging subsystem, the class that you use to get a Logger seems irrelevant as I tried with two different ones.
I run these lines as the first ones of the program in production code and in the tests to work properly in both contexts.
I was able to get it to work by setting the VM options as such:
-Dvertx.logger-delegate-factory-class-name=io.vertx.core.logging.Log4jLogDelegateFactory
Then in my log4j.properties, I had to add this:
log4j.category.io.vertx = TRACE
I know this question is getting a bit old, but the only way I was able to get the vertx LoggerHandler to not use JUL was to call LoggerFactory.initialise() after setting the system property as described in the question.
Even better, I set the property in my build.gradle, like so:
run {
systemProperty(
"vertx.logger-delegate-factory-class-name",
"io.vertx.core.logging.SLF4JLogDelegateFactory"
)
args = ['run', mainVerticleName, "--redeploy=$watchForChange", "--launcher-class=$mainClassName", "--on-redeploy=$doOnChange",
"-Dvertx.logger-delegate-factory-class-name=io.vertx.core.logging.SLF4JLogDelegateFactory" ]
}
And then at the very top of my MainVerticle::start I have:
LoggerFactory.initialise()
And, boom. Everything is now formatted correctly, including all the startup output.
I am running into logging issues after upgrading my Java EE app from Weblogic/JDeveloper to 12.1.2 to 12.1.3.
System.out.println is printing to the server log fine but log.info("test") is not. The logging works if I set the log level e.g. log.setLevel(Level.INFO). Here are my test results.
// This works
System.out.println("test1");
// Output when run: test1
// This does not work. Nothing prints to the server log
log.info("test2");
// The above works if I set the log level
log.setLevel(Level.INFO);
log.info("test3");
// Output when run: test3
// This prints null. It appears that logging level is set to null on server startup
System.out.println(" what is my current logging level: " + log.getLevel());
As per Oracle documentation if no logging configuration is provided then the default logging.properties in JDK/JRE/Lib is used. The default log level is INFO.
I have also tried to load up logging.properties and switch log4j but nothing works.
I don't want to set log level to something in every class. Is there a way to set this on server startup or debug what is causing/setting the logging level to null.
From the logger documentation:
The result may be null, which means that this logger's effective level will be inherited from its parent.
So you only have to set the level of the root logger. You should check that a ConsoleHandler is installed and that the level is set to INFO or lower. You should also check that writing to System.err shows up in the log file as that is the stream that is used for the ConsoleHandler.
I use this code for mine "Logg class" so every class is connected with it, so every exception from every class use this. if you have many classes you want to get logged from this is kind a smart and easy way. I just have one problem too, this code creates a txt file every time you run a program and it's connected with the Logg class. I will fix it soon, so i will edit this answer then. heres my code:
Top of class
private final static Logger logger = Logger.getLogger(Logg.class.getName());
private static FileHandler fh = null;
and in the method you can have this;
Properties prop = new Properties();
InputStream in = Logg.class.getResourceAsStream("loggconfig");
if (in != null) {
prop.load(in);
} else {
throw new FileNotFoundException("property file '" + in + "' not found in the classpath");
}
Some exemple, this txt file will be named the current year, date and time.
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm");
fh = new FileHandler((dateFormat.format(date) + ".log"), false);
Logger l = Logger.getLogger("");
fh.setFormatter(new SimpleFormatter());
l.addHandler(fh);
l.setLevel(Level.INFO);
have this under argument you want to logg:
logger.log(Level.WARNING, "Bla bla");
you can also have a file, like a config so you can choose what level you want to get logged. Then you need to create a property file, my is named loggconfig.
in the config file i have this code:
Level=WARNING
so it just every exception i have as a WARNING, i can change it to INFO to so i get everything logged. Smart to only use two levels in the code.
So if you want to use config file u need to change l.setLevel too this:
l.setLevel(Level.parse(prop.getProperty("Level")));
so it takes the level from config file.
I have the following example code :
import java.util.logging.Logger;
public class LoggingExample {
private static final Logger LOGGER = Logger.getLogger(
Thread.currentThread().getStackTrace()[0].getClassName() );
public static void main(String[] args) {
LOGGER.setLevel(Level.ALL);
LOGGER.info("Logging an INFO-level message");
LOGGER.fine("Logging an INFO-level message2");
}
}
With the output to console of:
05/06/2014 12:07:09 ztesting.Loger.LoggingExample main
INFO: Logging an INFO-level message
And I have several question:
The entire output is in red, can I set the output to be in different colors according to the level?
Can I not display the first line "05/06/2014 12:07:09 ztesting.Loger.LoggingExample main"
Can I block the output to console completely, meaning I would only set output to a log file.
Not as important, but why does the fine row does not display ?
P.S. I m using netbeans 6.9
ALSO tried using the following links and it got me no where
Is there any way to remove the information line from java.util.logging.Logger output?
How do I get java logging output to appear on a single line?
Thanks for any help ..
Most of your questions are answered in different tutorials available for java.util.logging. One example here
You should also read the javadoc.
"Can I not display the first line "05/06/2014 12:07:09 ztesting.Loger.LoggingExample main"
Yes, using Formatters
"Can I block the output to console completely, meaning I would only set output to a log file."
Yes, set the log level, filter or handler in a configuration file
"The entire output is in red, can I set the output to be in different colors according to the level?"
This is specific to Netbeans which I don't personally use so I can't answer that.
Personally I prefer SLF4J with Logback over JUL...
Some logging levels appear to be broke?
I run a Java web start (which I will begin to call JWS from now on) application straight from a GlassFish 3.1.2.2 instance. The client has a static logger like so:
private final static Logger LOGGER;
static {
LOGGER = Logger.getLogger(App.class.getName());
// Not sure how one externalize this setting or even if we want to:
LOGGER.setLevel(Level.FINER);
}
In the main method, I begin my logic with some simple testing of the logging feature:
alert("isLoggable() INFO? " + LOGGER.isLoggable(Level.INFO)); // Prints TRUE!
alert("isLoggable() FINE? " + LOGGER.isLoggable(Level.FINE)); // ..TRUE
alert("isLoggable() FINER? " + LOGGER.isLoggable(Level.FINER)); // ..TRUE
alert("isLoggable() FINEST? " + LOGGER.isLoggable(Level.FINEST)); // ..FALSE
My alert methods will display a JOptionPane dialog box for "true GUI logging". Anyways, you see the printouts in my comments I added to the code snippet. As expected, the logger is enabled for levels INFO, FINE and FINER but not FINEST.
After my alert methods, I type:
// Info
LOGGER.info("Level.INFO");
LOGGER.log(Level.INFO, "Level.INFO");
// Fine
LOGGER.fine("Level.FINE");
LOGGER.log(Level.FINE, "Level.FINE");
// Finer
LOGGER.finer("Level.FINER");
LOGGER.log(Level.FINER, "Level.FINER");
LOGGER.entering("", "Level.FINER", args); // <-- Uses Level.FINER!
// Finest
LOGGER.finest("Level.FINEST");
LOGGER.log(Level.FINEST, "Level.FINEST");
I go to my Java console and click on the tab "Advanced", then I tick "Enable logging". Okay let's start the application. Guess what happens? Only Level.INFO prints! Here's my proof (look at the bottom):
I've done my best to google for log files on my computer and see if not Level.FINE and Level.FINER end up somewhere on the file system. However, I cannot find the log messages anywhere.
Summary of Questions
Why does it appear that logging of Level.FINE and Level.FINER does not work in the example provided?
I set the logging level in my static initializing block, but I'd sure like to externalize this setting to a configuration file of some sort, perhaps packaged together with the EAR file I deploy on GlassFish. Or why not manually write in some property in the JNLP file we download from the server. Is this possible somehow?
Solution for problem no 1.
After doing a little bit more reading on the topic, I concluded that a logger in Java uses a handler to publish his logs. And this handler in his turn has his own set of "walls" for what levels he handles. But this handler need not be attached directly to our logger! You see loggers are organized in a hierarchical namespace and a child logger may inherit his parents handlers. If so, then By default a Logger will log any output messages to its parent's handlers, and so on recursively up the tree (see Java Logging Overview - Oracle).
I ain't saying I get the full picture just yet, and I sure didn't find any quotes about how all of this relates to a Java Web Start application. Surely there has to be some differences. Anyways, I did manage to write together this static initializing block that solves my immediate problem:
static {
LOGGER = Logger.getLogger(App.class.getName());
/*
* This logic can be externalized. See the next solution!
*/
// DEPRECATED: LOGGER.setLevel(Level.FINER);
if (LOGGER.getUseParentHandlers())
LOGGER.getParent().getHandlers()[0].setLevel(Level.FINER);
else
LOGGER.setLevel(Level.FINER);
}
Solution for problem no 2.
The LogManager API docs provided much needed information for the following solution. In a subdirectory of your JRE installation, there is a subdirectory called "lib" and in there you shall find a "logging.properties" file. This is the full path to my file on my Windows machine:
C:\Program Files (x86)\Java\jre7\lib\logging.properties
In here you can change a lot of flavors. One cool thing you could do is to change the global logging level. In my file, this was done on row 29 (why do we see only a dot in front of the "level"? The root-parent of all loggers is called ""!). That will produce a hole lot of output; on my machine I received about one thousand log messages per second. Thus changing the global level isn't even plausible enough to be considered an option. Instead, add a new row where you specify the level of your logger. In my case, I added this row:
martinandersson.com.malivechat.app.App.level = FINER
However, chances are you still won't see any results. In solution no 1, I talked about how loggers are connected to handlers. The default handler is specified in logging.properties, most likely on row 18. Here's how my line reads:
handlers= java.util.logging.ConsoleHandler
Also previously, I talked about how these handlers in their turn use levels for what should trouble their mind. So, find the line that reads something like this (should now be on row 44?):
java.util.logging.ConsoleHandler.level = INFO
..and in my case I swapped "INFO" to "FINER". Problem solved.
But!
My original inquiry into this matter still hasn't provided an answer how one can set these properties closer in par with the application deployment. More specifically, I would like to attach these properties in a separate file, bundled with the application EAR file I deploy on GlassFish or something like that. Do you have more information? Please share!