Is there a way to be notified of caught exceptions in an eclipse application?
I know that if I start an application using eclipse debugger, I can suspend execution upon caught and uncaught exceptions (see https://stackoverflow.com/a/3066280/228965). I guess this feature somehow uses JVMTI.
Now I have the following problem:
I have an eclipse application not written by me. I want to monitor this application. I have written some bundles to monitor different aspect of the application (user interactions, workbench changes, etc..). I start these bundles along the application using bundles.info file. Now I need to be notified whenever an exception happens. I added a listener to error log and this way I am notified of uncaught exceptions. However I want also to be able to be notified of "any" exception, even those that have been caught by the original developers.
Is there a way to achieve this?
You could investigate the logger of your application. If it use log4j, you could create an appender specific for exceptions and work with them.
Add a breakpoint to the constructors of java.lang.Exception (or maybe even Throwable, depending upon exactly what you're looking for).
All exceptions, even custom ones, must extend from one of these, so you can find each Exception as it is being created - and then even trace it through to see where it is being caught and handled (if at all).
Using AOP may also be a good option, but this approach doesn't require any modifications to the existing code - source code or byte code.
From JDK 1.5 you can use Thread.setDefaultUncaughtExceptionHandler() for exactly this purpose.
Related
Is there a way of debugging JSF + PrimeFaces applications by simply looking at one log file? To be more specific, here is how I personally do it at the moment if something doesn't work as expected:
Look for visual indicator on the Web page (e.g. if I receive HTTP 500 obviously something is wrong)
I look in the log file of my application server for any warnings, errors or stacktraces
I look in the Firebug's network console to see if there were any errors in the HTTP response; this tends to happen from time to time (and it's not shown in the log!)
I check if it is a validation error by including a p:message on the form and display it.
For me, checking for errors is a 4-step workflow. Is there a better way of doing this? Ideally, it would be great if all these errors could be logged to a single log. Is this DIY or there is some standard way of doing it?
Thanks!
There is nothing out of box that will give you what you describe because these are all situations that occur on different layers.
This is typically because an unhandled exception made its way up the call stack. If you improve your code for exception handling then these circumstances should be caught and logged.
Improved exception handling and logging at all application layers will help capture all errors and exceptions in a single log file on the application server.
Firebug catches network errors in asynchronous postbacks as well as Javascript exceptions. This is completely a client side concern as the server just derives the markup. It might be possible to catch all Javascript exceptions before they are propagated up to Firebug and to send an asynchronous error report to the server for the server to log. This shouldn't be too terribly difficult to implement.
Again, better logging in your validator methods will be able to put this information in the application server logs so that you have all of this information in one place.
The bottom line is that these are all situations where they become a non-issue for developers who learn how to intuitively include good Instrumentation code throughout their applications.
There is also <p:log /> that lets you use PrimeFaces debug.
See: http://www.primefaces.org/showcase/ui/misc/log.xhtml
Hi i am also developing an application using jsf and primefgaces. I also had faced this problem earlier. Now i am using log4j to log all the errors/exceptions/ doubts into a single file. It is also very easy to use it.You can have a look at it, it may solve your problems.
I'm using the most up-to-date version of Eclipse (Helios) for Java development. I've written a lot of code for my project, and I'm also using some 3rd-party code in the project.
It's normal for the 3rd-party code to internally throw exceptions, even when nothing is deeply wrong. It will catch these itself. During a normal run, the 3rd-party code might throw a lot of these not-really-a-problem Exceptions.
I'd like to tell Eclipse that, during debugging, it should break when any of my code throws an Exception, but not when other code I'm linking to throws an Exception. Does anyone know if Eclipse supports this?
I know Eclipse lets you break only when Exceptions of certain types are thrown, but that doesn't help when 3rd party code and my own both throw standard Exceptions.
AFAIK no. But you can set a root Exception and make all your exceptions extends it. Then you can set up a Exception Breakpoint on you root exception.
In the breakpoint window you can do so, there is an icon.
My team is using the "cmt-timeout-in-seconds" setting, in the "sun-ejb-jar.xml" file on a GlassFish 2.x server, to control the transaction timeout threshold for an EJB module.
I realize that this is a pretty broad question... but we're having issues (I'm not sure of all the details myself), and I've been asked to verify that the "cmt-timeout-in-seconds" actually is being used.
Does anyone know of a way to interrogate or determine this from the application server, short of writing new custom code to test it? I'm not even certain what kind of custom code I would write if I had to go down that path.
It seems that the most straightforward answer is simply to write a small test case. I just created a simple EJB, with a custom CMT timeout setting in "sun-ejb-jar.xml".
I then wrote a method on this EJB class, annotated to require its own new transaction. This method did three things: (1) write a log message, (2) use Thread.sleep() to pause execution for awhile, and (3) write a second log message.
By using sleep values that were greater than or less than the CMT timeout setting, I was able to confirm that the settings were being applied.
However, one interesting note that I learned from this... when a container-managed transaction times-out for an EJB3 method, it does not interrupt or halt the execution of that method! The method continues to execute (or stays hung), and the consequences of the timeout are not handled and logged until after the method returns. Interesting behavior, which can lead to some serious bugs if you're not aware of it. See this article for more detail.
I have a new puzzle for you :-).
I was thinking on how should an application handle his own start up. Like : checking for required libraries, correct versions, database connectivity, database compatibility, etc. To be specific, here is the test case. I use SWT and Log4J, for obvious reasons. Now, the questions :
Should the app check itself for the required dependencies? If yes, should the user be given specific details of what it's missing? Or just a message, and details to the logs?
What if the log4J library is unavailable?
What is the best to do the test? Verifying the file existance (using file.exists(), at specified path), or loading a class, say Class.forName("org.apache.log4j.Logger")? What should be the proper order to do the checks? For instance, if i test for SWT, i have no idea if logger is available or not, and the error will occur when i try to access that. Backwards, if i test for the logger 1st : a) The lib could be unavailable - i cannot log the error; b) SWT could be unavailable - unable to display the user message.
I've discovered apache.commons.lang framework today, and i find very useful the method org.apache.commons.lang.SystemUtils.isJavaVersionAtLeast(Float value)
, and manny others, i am sure. However, importing too much libs to your project dont make it hard to maintain? Versions change, compatibilities are lost, eg. one cannot control a 3rd party developement style or direction.
Thank u for your answers.
I agree with your need. Checking for required runtime environment provides:
immediate feedback, instead of randomly breaking when accessing some functionnality
hopefully more skilled user, as the immediate feedback is available to the guy that is installing the software, hopefully more skilled than an average user, or at least less confident (installing is always a special operation). A more skilled user is less disturbed if the error is coming in the console, he doesn't depend on a graphical interface.
improved reporting : the error message can be explicit (you're in charge), while default error messages come in many flavours (they are not always that helpful on 1. what's wrong 2. suggesting a fix).
But please note that the runtime requirements could be checked in two situations:
when installing : long verifications are always acceptable ; if a library is not here, a required database or WebService is not accessible, it won't be here at runtime either, so you can complain immediately.
when starting the execution : you can verify again (and some verifications may only happen at that point)
This suggests creating an installer for your application.
Potentially, errors would not all be blocking for the installation. Some would rather accumulate as a list of tasks to be done after installation, maybe nicely formatted in a file with all reference information.
Here, we once again hit the notion of error level in validation (similar to what happens for Log4j) : some validation errors are at fatal level, others are errors, possibly also warnings ...
In our projects, we have some sort of initialization and validation going on on startup. Based on our day-to-day experience, I would suggest the following:
When the application gets big, you don't want to have all init centralized in one class, so we have a modular structure.
A small kernel is configured with a list of modules classes. It's whole init sequence is under strict control, ready for any exceptions (translating them to appropriate messages, but memorizing the stack traces that are so useful to the developpers), making no assumption on the available libraries and so on... CheckStyle can be configured specially for this code.
The interface (of course, abstract class is possible) that the modules implement typically have several initialization methods. They could be:
getDependencies : returns a list of modules that this one depends on.
startup : when the whole application is starting. This will be called only once during startup, and cannot be called again.
start : when the module gets ready for regular operation
stop : reverse from start
shutdown : reverse from startup.
The kernel instanciates each of the module in turn. Then he calls one init method on all of them, then another init method and so on as needed. Each init method can:
signal error conditions (using levels, like Log4J).
an exception thrown would be caught by the kernel, and translated to an error condition
consult another module for its status (because dependencies are the general case), and react accordingly. If needed, the dependencies could be made declaratively.
The kernel takes care of module dependencies generically:
He sorts the modules so that dependencies are respected.
He doesn't initialize a module if one of its dependencies couldn't make it.
If asked to stop a module, he will first stop the modules that depends on it.
A nice feature of this kernel approach is that it is easy to aggregate the errors, at various levels (although fatal could stop it), and report all of them at the end, using whatever means is available (SWT or not, Log4J or not ...). So instead of discovering the problems one after the other, and having to start again each time, you could deliver in one blow (nicely prioritized of course).
Concerning your precise questions:
Should the app check itself for the required dependencies?
Yes (see higher)
If yes, should the user be given specific details of what it's missing? Or just a message, and details to the logs?
As said higher, when installing the user is more prepared to deal with this.
When starting, we use an easy message for the end-user, but give access to the full stack traces for the developper (we have a button that copies in the clipboard the application environment, the stack traces and so on).
What if the log4J library is unavailable?
Log without it (see higher).
What is the best to do the test? Verifying the file existance (using file.exists(), at specified path), or loading a class, say Class.forName("org.apache.log4j.Logger")?
I would load a class. But if it failed, I might check the file existence on disk to give a improved message, including "how to fix".
What should be the proper order to do the checks? For instance, if i test for SWT, i have no idea if logger is available or not, and the error will occur when i try to access that. Backwards, if i test for the logger 1st : a) The lib could be unavailable - i cannot log the error; b) SWT could be unavailable - unable to display the user message.
As I said higher, I suggest these low-level errors get accumulated in a small area of code (kernel), where you could use anything that is available to display them. If nothing is available, you could simply log in the console without Log4J.
The short answer is no. The JVM appropriately handles this functionality on initialization, or at runtime. If a required class is not found on the classpath, a ClassNotFoundException will be thrown. If a class was found, but a required method was not, a NoSuchMethodException is thrown.
Regarding 1 through 3 , there are 2 main use cases here:
application packaging is under your control, and can make sure that all required dependencies are packaged properly. Run-time validations are not useful here.
application packaging is not under your control, and you deliver the main jar and the instructions on what the requirements are. Run-time validations might be useful, but someone who wants to package your application usually has enough skill to understand what a ClassNotFoundException: org.apache.logging.LogManager means.
Regarding 4, as long as you keep the same version of the dependency included in your project, you will have no problems in keeping control. Upgrading to a newer version is a conscious decision, which requires thought and testing.
I'm using the Enerjy (http://www.enerjy.com/) static code analyzer tool on my Java code. It tells me that the following line:
System.err.println("Ignored that database");
is bad because it uses System.err. The exact error is: "JAVA0267 Use of System.err"
What is wrong with using System.err?
Short answer: It is considered a bad practice to use it for logging purposes.
It is an observation that in the old times when there where no widely available/accepted logging frameworks, everyone used System.err to print error messages and stack traces to the console. This approach might be appropriate during the development and local testing phase but is not appropriate for a production environment, because you might lose important error messages. Because of this, in almost all static analysis tools today this kind of code is detected and flagged as bad practice (or a similarly named problem).
Logging frameworks in turn provide the structured and logical way to log your events and error messages as they can store the message in various persistent locations (log file, log db, etc.).
The most obvious (and free of external dependencies) hack resolution is to use the built in Java Logging framework through the java.util.logging.Logger class as it forwards the logging events to the console by default. For example:
final Logger log = Logger.getLogger(getClass().getName());
...
log.log(Level.ERROR, "Something went wrong", theException);
(or you could just turn off that analysis option)
the descriptor of your error is:
The use of System.err may indicate residual debug or boilerplate code. Consider using a
full-featured logging package such as Apache Commons to handle error logging.
It seems that you are using System.err for logging purposes, that is suboptimal for several reasons:
it is impossible to enable logging at runtime without modifying the application binary
logging behavior cannot be controlled by editing a configuration file
problably many others
Whilst I agree with the points above about using a logging framework, I still tend to use System.err output in one place: Within shut-down hooks. This is because I discovered that when using the java.util.logging framework log statements are not always displayed if they occur in shut-down hooks. This is because the logging library presumably contains its own shutdown hook to clean up log files and other resources, and as you can't rely on the order in which shutdown hooks run, you cannot rely on java.util.logging statements working as expected.
Check out this link (the "Comments" section) for more information on this.
http://weblogs.java.net/blog/dwalend/archive/2004/05/shutdown_hooks_2.html
(Obviously the other alternative is to use a different logging framework.)
System.err is really more for debugging purposes than anything else. Proper exception handling and dealing with errors in a manner that is more user-friendly is preferred. If the user is meant to see the error, use a System.out.println instead.
If you want to keep track of those errors from a developer's standpoint, you should use a logger.
Things written to System.err are typically lost at runtime, so it is considered a better practice to use a logging framework that is more flexible about where to output the message, so it can be stored as a file and analyzed.
System.err and System.out for non-console applications is only ever seen by the developer running the code in his or her IDE, and useful information may get lost if the item is triggered in production.
System.err.println and System.out.println should not be used as loggging-interface. STD-Output and STD-Error (these are written by System.out and .err) are for messages from command-line-tools.
System.err prints to the console. This may be suitable for a student testing their homework, but will be unsuitable for an application where these messages won't be seen (Console only store so many lines).
A better approach would be to throw an exception holding the message that would normally get sent to the console. An alternative to this would be use third party logging software which would store this messages in a file which can be stored forever.