Monday, January 31, 2011

How to use logger in your Java application

How to log Messages in your application?

Java's logging facility has two parts: a configuration file, and an API for using logging services. It is suitable for simple and moderate logging needs. Log entries can be sent to the following destinations, as either simple text or as XML:
· The console
· A file
· A stream
· Memory
· TCP socket on a remote host

The LEVEL class defines seven levels of logging enlightenment :
FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE .ALL and OFF are defined values as well

The levels in code may be modified as required :
· Upon startup, by using CONFIG to log configuration parameters
· During normal operation, by using INFO to log high-level "heartbeat" information
· When bugs or critical conditions occur, by using SEVERE.
· Debugging information might default to FINE, with FINER and FINEST used occasionally, according to user need.

There is flexibility in how logging levels can be changed at runtime, without the need for a restart:
· By simply changing the configuration file and calling LogManager.readConfiguration.
· By changing the level in the body of code , using the logging API ;
For example, one might automatically increase the logging level in response to unexpected events

The logging levels are in descending order SEVERE, WARNING, INFO, CONFIG, FINE, FINER and FINEST. If we specify log level as

INFO then all the log messages which are equal to INFO and greater (WARNING, SEVERE) levels will be logged.

Levels are attached to the following items:
· An originating logging request (from a single line of code)
· A Logger (usually attached to the package containing the above line of code)
· A Handler (attached to an application)

Here is an example of a logging configuration file :
# Properties file which configures the operation of the JDK
# logging facility. # The system will look for this config file, first using
# a System property specified at startup:
# >java -Djava.util.logging.config.file=myLoggingConfigFilePath #
# If this property is not specified, then the config file is retrieved
# from its default location at:
# JDK_HOME/jre/lib/
# Global logging properties.
# ------------------------------------------
# The set of handlers to be loaded upon startup.
# Comma-separated list of class names.
# (? LogManager docs say no comma here, but JDK example has comma.)
handlers=java.util.logging.FileHandler, java.util.logging.ConsoleHandler

# Default global logging level.
# Loggers and Handlers may override this level

# Loggers
# ------------------------------------------
# Loggers are usually attached to packages.
# Here, the level for each package is specified.
# The global level is used by default, so levels
# specified here simply act as an override.

# Handlers
# -----------------------------------------
# --- ConsoleHandler ---
# Override of global logging level

# --- FileHandler ---
# Override of global logging level
# Naming style for the output file:
# (The output file is placed in the directory
# defined by the "user.home" System property.)

# Limiting size of output file in bytes:

# Number of output files to cycle through, by appending an
# integer to the base file name:

# Style of output (Simple or XML):

Here is an example of using the logging API :

import java.util.logging.*;
* Demonstrate Java's logging facilities, in conjunction
* with a logging config file.
public final class SimpleLogger {

  public static void main(String argv[]) {
    SimpleLogger thing = new SimpleLogger();
   public void doSomething() {
   //Log messages, one for each level
   //The actual logging output depends on the configured
    //level for this package. Calls to "inapplicable"
    //messages are inexpensive.
     fLogger.finest("this is finest");
    fLogger.finer("this is finer");
    fLogger.fine("this is fine");
    fLogger.config("this is config");"this is info");
    fLogger.warning("this is a warning");
    fLogger.severe("this is severe");

    //In the above style, the name of the class and
    //method which has generated a message is placed
    //in the output on a best-efforts basis only.
    //To ensure that this information is always
    //included, use the following "precise log"
    //style instead :
    fLogger.logp(Level.INFO, this.getClass().toString(), "doSomething", "blah");

    //For the very common task of logging exceptions, there is a
    //method which takes a Throwable :
    Throwable ex = new IllegalArgumentException("Some exception text");
    fLogger.log(Level.SEVERE, "Some message", ex);

    //There are convenience methods for exiting and
    //entering a method, which are at Level.FINER :
    fLogger.exiting(this.getClass().toString(), "doSomething");

    //Display user.home directory, if desired.
    //(This is the directory where the log files are generated.)
    //System.out.println("user.home dir: " + System.getProperty("user.home") );

  // PRIVATE //

  //This logger will inherit the config of its parent, and add
  //any further config as an override. A simple style is to use
  //all config of the parent except, perhaps, for logging level.

  //This style uses a hard-coded literal and should likely be avoided:
  //private static final Logger fLogger = Logger.getLogger("");

  //This style has no hard-coded literals, but forces the logger
  //to be non-static.
  //private final Logger fLogger=Logger.getLogger(this.getClass().getPackage().getName());

  //This style uses a static field, but hard-codes a class literal.
  //This is probably acceptable.
  private static final Logger fLogger = Logger.getLogger(SimpleLogger.class.getPackage().getName());


Friday, January 28, 2011

How to log an exception's stackTrace to log file using logger

Manytimes, we use logger to log messages that help us while debugging our application.
But, do you know, how do we write exception stackTrace to log file?

I tried to look for methods in Exception object, there is a method that writes to PrintWriter. Now how do I get PrintWriter's Object? Definitely, i could use reponse.getWriter(), but what if i want to log stacktrace from a java file, where I do not have access to response object. Moreover in many scenario's I would not like to write the stacktrace to browser, visible to end user.

Then I found a very useful over loaded method, which got skipped everytime before today.

Logger has an overloaded method, with 2 arguments, the second one is object of Throwable or Exception class.

This can be achieved as follows

 } catch( Exception e ) {
 logger.debug( e.getMessage(), e );

Wednesday, January 26, 2011

How to download a file using AJAX

I struggled for half of my day finding this.

Actually in our project, there is a CART. The requirement is when we click on downloadCart button, it should download the contents of the cart and clear the cart as well.

The first issue that I faced was...

As the response has a zip file to be downloaded, hence in our Action class, they were writing bytes to the response, and in the end, when they return SUCCESS, (I forgot to tell u, we are using struts in our project) it gives an exception : java.lang.illegalStateException, that is expected.

So, what's the solution...

After discussing this with my friend Sukhbir, he suggested that we can't return any view after we have committed the response. But how to handle this scenario.

He suggested, make 2 calls, using javascript, and put it on onClick event of the button.
One for downloading, and the second one for re-loading the cart (So that it gets refreshed).

I did the code for downloading using AJAX.... $.get and $.ajax
But the issue now came up was....

Ajax calls work in background and it doesn't lets the user see that something has response, no prompt.......nothing........

Now what??

Then I came to know that there are APIs available in jquery for handling binary data when data is coming from server. I googled this also a lot, but, couldn't find anything that worked for me.

I found a very pretty and simple solution on internet now...Here it is...
Thanks to Eric for this help

Source : Google Group Forums Link

Final Solution
function test(url){ 
  var elemIF = document.createElement("iframe"); 
  elemIF.src = url; = "none"; 

Related posts :

How to reload an iframe from within its source


Today I had a requirement where it was desired that on click of a button an iframe should get re-loaded and that button was within the source of that iframe.

I tried everything else on google, but nothing worked.

Finally I found this and it worked


Here is the complete code...

 <iframe src="def.html" id="cartFrame"></iframe><BR><BR>

  <!-- Remember, you must be connected to internet to make it work -->
  <script type="text/javascript" src=""></script>
  <script type="text/javascript">
    var d = new Date();
    // set the HTML content of the element with id=time
    // define what happens on click of the element with id="download"
     // Simply re-load myself :)

  <div id="time"></div><BR><BR>
  <button id="download">Download</button>

Thursday, January 20, 2011

Find bugs in your java program

You must be wondering, how to check errors and problems in your application.

Now your worry has come to an end..

Here is a tool, that can analyze compiled versions of your java programs and lets you know, what needs to be fixed in your application.

Have a look

Sunday, January 16, 2011

How to write this in jquery “window.parent.document.getElementById('parentPrice').innerHTML”?

I have an iframe and I wrote this code


to access parent element. How to get the same result using jquery?
UPDATE: Or how to access iFrame parent page using jquery?

To find in the parent of the iFrame use:

$('#parentPrice', window.parent.document).html();

The second parameter for the $() wrapper is the context in which to search. This defaults to document.

Courtesy :

Thursday, January 13, 2011

Common pitfalls in Javascript

When you defined script tag in JS

Define it as follows
<script type="text/javascript" src="jquery.js"></script>

And not as
<script type="text/javascript" src="jquery.js"/>

In the second case, it'll not interpret the script tag appropriately and the function defined inside <script>

Tuesday, January 11, 2011

Remove duplicate elements from a comma seperated list (JAVASCRIPT)

 var input = 'a,b,b,said,said, t, u, ugly, ugly';
 var splitted = input.split(',');
 var collector = {};
 for (i = 0; i < splitted.length; i++) {
    key = splitted[i].replace(/^\s*/, "").replace(/\s*$/, "");
    collector[key] = true;
 var out = [];
 for (var key in collector) {
 var output = out.join(',');

Sunday, January 9, 2011

Error 53 SQL Server 2005

Have you recently changed your machine name??

If you face this error while connecting to SQL server, here is the solution

Make sure that the Server Name matches the name of the machine you are trying to connect.

To get your machine name, right click My Computer -> Properties and there you can find Computer Name.

Saturday, January 8, 2011

Not enough arguments [nsIDOMWindowInternal.alert]

 <script type="text/javascript">
  function callfn()
<body onload="javascript:callfn()">

This will give error somewhat similar to

uncaught exception: [Exception... "Not enough arguments [nsIDOMWindowInternal.alert]" nsresult: "0x80570001 (NS_ERROR_XPC_NOT_ENOUGH_ARGS)" location: "JS frame :: :: :: line 810" data: no]

Please note that this error appears specifically in Firefox. (Not sure about other browsers).

Source :

Wednesday, January 5, 2011

JSON, AJAX and jQuery

Today I was working on JSON.
1) Requirement was to get the data from a server in a JSON object. Store it into request object.
2) And on an HTML page, it was required to fire an AJAX request, get the data from the Servlet created in step 1.

3) When i fired a request to servlet directly in browser window, it used to print JSON object that it returns. But when i make a request thru AJAX call... the data is never displayed.


JSON object must follow the structure of the JSON object.
You cannot add any extra println in the resulting JSP. It must ONLY and ONLY print JSON object.

You can validate your JSON from

See more :