I'm writing a Java class which plugs into a larger framework. Somewhere upstream, the code is redirecting System.out to somewhere other than standard out, but I really want to print a debugging message to standard out. Is there a way for me to get a hook back into standard out?
Perhaps an easier solution is to use System.err instead of System.out for debugging messages? It would be a lot easier and would not introduce any side-effects of that redirection.
Why not use System.err?
The most straightforward solution I see is just store System.out somewhere in your class before calling the library.
After looking around a bit, you should be able to use System.console().printf(...).
You can simply write:
System.setOut(System.out);
Related
I want to get the Console Log of the Kryonet as String so that i can display it in a TextArea.
Now my question, is there a way to do it?
I'm stuck at this problem..
Any suggestions would be so much appreciated.
Thanks
From the Kryonet documentation:
KryoNet makes use of the low overhead, lightweight MinLog logging library.
So looking at MinLog, which is just one source file, you just need to extend Logger to override the print method, and then call
Log.setLogger(new DifferentLoggerImplementation());
I'm trying to debug/trace how some Java code is executed (or if it even is). I would like a simple way to do an alert just so I can tell how the code is being executed. Something like:
alert ("do we get here");
in javascript, or:
echo ("do we get here");
in php.
I have googled it but alot of the methods seem fairly complicated and an excessive amount of code. I am new to java, is there any way to achieve this?
JOptionPane.showMessageDialog(null, "Your Message");
The null part can actually be switched by a proper parent component, if there is one.
You can use
System.out.println("Here we are");
but if you want to know how we got there you can use
new Throwable("Here we are").printStackTrace(System.out);
and it will print the call stacka s well.
Sytem.out.println("do we get here");
If you just want to do text output to the screen, you could just use System.out.println("Point 1");. If you are after a more visual thing (which I am assuming you are), you could take a look at the JOptionPane class, with more information available here.
A more traditional (an most likely preferred) way of doing something like what you are after would be use Loggin. SLF4J is a relatively popular way of doing logging in a Java application.
I want to hook the method System.out.print in Java and have the ability to read/change the variables used in the method before the part of the method is called that actually adds the string to whatever the output stream is.
In C++ I would just detour the function, or set an int3 instruction so I could access the registers but in java I have no idea how to accomplish something similar.
You can rewrite the byte code of the methods, and in the process capture/change the local variables. It is not trivial. See some notes here.
Maybe what you really want is a java debugger? You can connect a debugger to a remote process, add a breakpoint, and capture/change the local variables pretty easily using eclipse.
What is the real problem you are trying to solve?
Have a look at this link.
He sneakily defines a static anonymous class so that System.out points to something different, and therefore print and println will route through that object.
You can reassign System.out (and System.err) to another object which does what you want to do with it. Said object usually gets the old System.out value so that output can be made in the end.
This is usually done in main() and influences the whole JVM.
We use this to have automatic wrapping at 130 columns in a very peculiar setting where longer lines are truncated.
Since JDK 1.1, the System.setOut and System.setErr methods are added to enable applications to hook the streams.
Link : http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#setOut(java.io.PrintStream)
http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#setErr(java.io.PrintStream)
#Nowayz Some time before i too had the same problem with me.
After some research i came to know About AOP. AOP i.e. AspectJ provides a facility to intercept the java APIs by applying the pointcuts before,after, around. So have a look at it .You can refer my question on stack .it may help you.
Do System.out.println(...) calls pose any effect if left in BlackBerry code or any other programming language?
When removed, the compilation time may be reduced, but is there any particular other reason to remove them?
There are a couple of things you need to know before using System.out.println() on Blackberry:
Once you print out something to the standard output any person that has your application installed on the device will be able to see them. All they need to do is to attach the device to the simulator and run in debug mode. So make sure you do not print out anything sensitive such as passwords, class names etc. in the released application.
The performance overhead that the System.out.println() itself makes is minimal, especially when the output stream is not attached to anything (i.e. Device is not connected and not in debug mode).
I myself rather use Blackberry preprocessor to be able to disable all logs before making a release. For this reason I define a logging directive LOGGING and then in my code:
//#ifdef LOGGING
System.out.println("LOGGING is enabled");
//#endif
For more on how to use preprocessors in Blackberry Eclipse plugin see this.
I prefer to use a flag to disable sysouts. Sysouts are really slow if you use them a lot, eg. in loops.
If you don't intend to use the output for anything like debugging ect. then it's best to take it out. Your program will only run as fast as the line can be output so in theory the less system.out line you have the faster the process will be.
Hope this helps.
Runtime might be also reduced, as the statements are actually executed - even if the user doesn't see the output on the screen. If you're using a lot of these (e.g. in tight loops) or you're passing to them Objects with expensive toString() methods, the useless output may be slowing you down.
Also, if you're passing String as an argument, those will take some space in bytecode and in memory. You on your souped-up machine with 173 PB of RAM may not care, but there are resource-constrained systems (such as mobile devices).
You should be able to use Ant to preprocess these lines out of your source code. (Make sure that none of them have side-effects!)
I don't know specifically about Blackberry, but if your program is writing to an unknown device (i.e. you are not sure where standard out is going), there may be a potential for your app to occasionally/sporadically/inexplicably block momentarily in the attempt to write.
Create your own method, i.e. :
public static void consoleMessage(String msg){
if(DEBUG_FLAG){
System.out.println(msg);
}
}
Then use only this throughout your code. It will save you the time for changing all the lines.
Use something like Log4J instead of system out print statements, it gives you much more flexibility
Keeping System.out statements isn't that bad a thing to do usually. Users might be able to see them so it doesnt always look good in a production environment. A better idea is to use a logging framework such as java.util.logging or log4j. These can be configured to dump output to the console, to a file, a DB, a webservice ...
Keep in mind that just becuase you can't see the output it doesn't mean that no work is being done at runtime. The JVM still has to create a String to pass to system.out (or a log statement) which can take a fair bit of memory/CPU for large/complex objects like collections.
Sysout statements access a synchronized, shared resource, which causes synchronization between threads using it. That can prevent memory consistency bugs in multithreaded programs if there is no other code which enforces synchronization. When the sysout statements are removed, any existing memory consistency bugs in the code may surface for the first time.
For an example of this effect, see: Loop doesn't see changed value without a print statement.
It's not an object and it doesn't have any memory attached to it so there shouldn't be any effect besides the time to run it and compile it. And of course readability maybe lol
Some days ago I realized that PrintWriter (as well as PrintStream) never throw an IOException when writing, flushing or closing.
Instead it sets an internal flag (trouble=true) when an error occurs.
It's not possible to get the exact exception, but only if there was some exception (checkError()).
My question is: why would one want to have such behavior? Isn't that bad API design?
I think that since System.out and System.err are instances of PrintStream, some more relaxed error handling was provided. This was probably, as other posters have mentioned, to smooth the way for those transitioning from C/C++ circa 1995. When the Reader/Writer API was added, PrintWriter was created to parallel the existing PrintStream.
One application where this behavior is extremely desirable is logging. Logging is ancillary to a larger application. Typically, if logging fails, one doesn't want that the entire application to fail. Thus, it makes sense for System.err, at least, to ignore exceptions.
I wonder if its because IOExceptions are checked, this would require you placing a try catch block around every System.out. call.
update: Or a throws in your method signature.
That would get annoying very quickly.
I don't really know the story, but I think it was to make Java easier for newer programmers who the designers wanted to be able to use simple stdio printing methods without the need to know what exceptions are. So in that regard it is good design (I agree with you somewhat though).
Sun / Oracle should have added two write-like functions, one that throws an IOException and another that doesn't throw anything.
It's possible that the design was done by someone coming from a C background where stdio errors are handled in a similar fashion. Since I'm used to that paradigm, I wouldn't call it bad, but I'd agree that it is inconsistent.
I also agree with the comment about trying to make PrintWriter easier to use. The IO classes in Java are confusing (at least for everyone I know) and perhaps someone was just trying to make life a little bit easier.
It is not a design error. It is a proper design meant to be used in a situation when you write an output and you want errors to be ignored.
As a typical use case, the System.out and System.err were already mentioned, but the reason is not relaxed handling for convenience or smooth C/C++ transitions . It is a desired handling of a situation like this:
you start an application in a console
it produces output to the std out/err
you close the console, but you want the application to continue in the background
In this situation, depending on the system implementation, it could happen that System.out or System.err would fail after the console is closed, but you don't want that to crash your application. The application is wanted to continue to run in the background and the output is meant to be scraped. That's what PrintWriter does.
If you care about errors during the output, use FileWriter or OutputStreamWriter.
If you need some of the methods available in PrintWriter and not available in FileWriter, create your own TextWriter extending FileWriter or OutputStreamWriter.