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).
Related
I'm trying to set up slf4j.
When I simply print an information and an error, I get the following output:
FATAL: [http-thread-pool::http-listener-1(5)] INFO com.company.myclass - this is an information
FATAL: [http-thread-pool::http-listener-1(5)] ERROR com.company.myclass - this is an error
Except of the words INFO and ERROR, there are similar, they even have the same color - red.
Is this really the desired output?
Shouldn't INFO have another color, so that one can keep them apart?
This is my code:
Logger log = LoggerFactory.getLogger(this.getClass());
log.info("this is an information");
log.error("this is an error");
I added this Maven dependecy: SLF4J Simple Binding ยป 1.7.25.
You get the message in red because slf4j-simple uses by default the System.err as the default output when logFile is not defined private static String LOG_FILE_DEFAULT = "System.err"; You can check it on source code.
If you want your messages to be printed in white you can specify your output using the following argument -Dorg.slf4j.simpleLogger.logFile=System.out in this case System.err will be replaced by System.out.
If you choose instead an other log library such as Log4j and provide a configuration file you'll notice that logs will appear also in white.
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!
I'm working on building an Android app and I'm wondering what the best approach is to debugging like that of console.log in javascript
The Log class:
API for sending log output.
Generally, use the Log.v() Log.d() Log.i() Log.w() and Log.e()
methods.
The order in terms of verbosity, from least to most is ERROR, WARN,
INFO, DEBUG, VERBOSE. Verbose should never be compiled into an
application except during development. Debug logs are compiled in but
stripped at runtime. Error, warning and info logs are always kept.
Outside of Android, System.out.println(String msg) is used.
Use the Android logging utility.
http://developer.android.com/reference/android/util/Log.html
Log has a bunch of static methods for accessing the different log levels. The common thread is that they always accept at least a tag and a log message.
Tags are a way of filtering output in your log messages. You can use them to wade through the thousands of log messages you'll see and find the ones you're specifically looking for.
You use the Log functions in Android by accessing the Log.x objects (where the x method is the log level). For example:
Log.d("MyTagGoesHere", "This is my log message at the debug level here");
Log.e("MyTagGoesHere", "This is my log message at the error level here");
I usually make it a point to make the tag my class name so I know where the log message was generated too. Saves a lot of time later on in the game.
You can see your log messages using the logcat tool for android:
adb logcat
Or by opening the eclipse Logcat view by going to the menu bar
Window->Show View->Other then select the Android menu and the LogCat view
console.log() in java is System.out.println(); to put text on the next line
And System.out.print(); puts text on the same line.
public class Console {
public static void Log(Object obj){
System.out.println(obj);
}
}
to call and use as JavaScript just do this:
Console.Log (Object)
I think that's what you mean
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);