Saturday, 2 August 2014

Logging Levels

Set of standard logging levels are provided by Java, to control logging output. Enabling logging at given level also enables logging at higher levels.

Below are the logging levels offered by logging package in descending order.

SEVERE (highest value)
WARNING
INFO
CONFIG
FINE
FINER
FINEST (lowest value)

If you enable logging at level 'INFO', then it enables logging for higher levels (WARNING, SEVERE) by default. We are allowed to set logging levels to both handlers and loggers.

import java.io.IOException;
import java.util.logging.*;

public class LoggingLevels {
    static final Logger log = Logger.getLogger("MyLog");
    static FileHandler fileHanlder1, fileHanlder2, fileHanlder3;
    static FileHandler fileHanlder4, fileHanlder5, fileHanlder6;
    
    static void doLogging(){
        log.severe("I am SEVERE Message");
        log.warning("I am WARNING Message");
        log.info("I am INFO Message");
        log.fine("I am FINE Message");
        log.finer("I am finer Message");
        log.finest("I am finest Message");
    }
    public static void main(String args[]) throws IOException{
        fileHanlder1 = new FileHandler("handle1.out");
        fileHanlder2 = new FileHandler("handle2.out");
        fileHanlder3 = new FileHandler("handle3.out");
        fileHanlder4 = new FileHandler("handle4.out");
        fileHanlder5 = new FileHandler("handle5.out");
        fileHanlder6 = new FileHandler("handle6.out");
        
        log.addHandler(fileHanlder1);
        log.addHandler(fileHanlder2);
        log.addHandler(fileHanlder3);
        log.addHandler(fileHanlder4);
        log.addHandler(fileHanlder5);
        log.addHandler(fileHanlder6);
        
        fileHanlder1.setLevel(Level.SEVERE);
        fileHanlder2.setLevel(Level.WARNING);
        fileHanlder3.setLevel(Level.INFO);
        fileHanlder4.setLevel(Level.FINE);
        fileHanlder5.setLevel(Level.FINER);
        fileHanlder6.setLevel(Level.FINEST);
        
        log.setLevel(Level.FINE);
        
        doLogging();
        
        fileHanlder1.close();
        fileHanlder2.close();
        fileHanlder3.close();
        fileHanlder4.close();
        fileHanlder5.close();
        fileHanlder6.close();
        
    }
}

Run the above program, you will see the below messages in console.

Jul 24, 2014 3:59:38 PM logger.LoggingLevels doLogging
SEVERE: I am SEVERE Message
Jul 24, 2014 3:59:38 PM logger.LoggingLevels doLogging
WARNING: I am WARNING Message
Jul 24, 2014 3:59:38 PM logger.LoggingLevels doLogging
INFO: I am INFO Message

Below files are created.
handle1.out : Contains only SEVERE Messages, since Level is set to SEVERE.
handle2.out : Contains Only SEVERE and WARNING Messages since Level is set to WARNING.
handle3.out : Contains Only SEVERE, WARNING and INFO Messages since Level is set to INFO.
handle4.out : Contains only SEVERE, WARNING, INFO and FINE messages. Since Level is set to FINE.
handle5.out and handle6.out contains only SEVERE, WARNING, INFO and FINE messages, even though their Level supports FINER and FINEST respectively. It is because above program set log level to FINE.

log.setLevel(Level.FINE)
Above statement sets the log level to FINE. So all the messages higher than or equal to FINE are processed by this logger. Message levels lower than this value will be discarded

Note:
In addition to the above logging levels, two more also supported.
a. OFF : used to turn off logging
b. ALL : used to enable logging of all messages.





Prevoius                                                 Next                                                 Home

Handler

A Handler object takes logger messages from a logger and export them to destinations like file, console, send them to a network logging service etc.,

ConsoleHandler, FileHandler, SocketHandler are some of the useful handlers available in java.util.logging package.


As you observe the above figure, logger sends the log messages to handler. Logger can add any number of handlers to it. In the below program, we add two handlers (file and console) to the logger. Logger creates a log record and send it to the registered handlers. Handler take these logger messages and export them to destinations like file, console etc.,

import java.io.IOException;
import java.util.logging.*;

public class LoggingUsingHandler {
    static final Logger log = Logger.getLogger("MyLog");
    static ConsoleHandler conHandler = new ConsoleHandler();
    static FileHandler fileHanlder;
    
    static void processData(){
        log.info("Started Processing Data");
        /* Do Processing here */
        log.info("Finished processing data");
    }
    
    public static void main(String args[]) throws IOException{
        fileHanlder = new FileHandler("fileLog.out");
        
        log.addHandler(conHandler);
        log.addHandler(fileHanlder);
        
        processData();       
    }
}

Output
Jul 24, 2014 2:58:07 PM logger.LoggingUsingHandler processData
INFO: Started Processing Data
Jul 24, 2014 2:58:07 PM logger.LoggingUsingHandler processData
INFO: Started Processing Data
Jul 24, 2014 2:58:07 PM logger.LoggingUsingHandler processData
INFO: Finished processing data
Jul 24, 2014 2:58:07 PM logger.LoggingUsingHandler processData
INFO: Finished processing data

A file named ' fileLog.out' is created and stores all the logging messages.

static ConsoleHandler conHandler = new ConsoleHandler();
Above statement creates a console handler, which sent log messages to console.

fileHanlder = new FileHandler("fileLog.out");
Above statement creates a file name fileLog.out and send the log messages to this file.

The contents of 'fileLog.out' looks like below.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
<date>2014-07-24T14:55:32</date>
<millis>1406193932196</millis>
<sequence>0</sequence>
<logger>MyLog</logger>
<level>INFO</level>
<class>logger.LoggingUsingHandler</class>
<method>processData</method>
<thread>1</thread>
<message>Started Processing Data</message>
</record>
<record>
<date>2014-07-24T14:55:32</date>
<millis>1406193932230</millis>
<sequence>1</sequence>
<logger>MyLog</logger>
<level>INFO</level>
<class>logger.LoggingUsingHandler</class>
<method>processData</method>
<thread>1</thread>
<message>Finished processing data</message>
</record>
</log>

log.addHandler(conHandler);
log.addHandler(fileHanlder);

Above two statements add handlers to this particular logger.


Prevoius                                                 Next                                                 Home

Simple Logger Example

import java.util.logging.*;

public class SimpleLogging {
    static final Logger log = Logger.getLogger("Simple Log");
    
    void processData(){
        log.info("About to start processing data");
        /* Do some processing here */
        log.info("Finished procesing data");
    }
    public static void main(String args[]){
        SimpleLogging myLog = new SimpleLogging();
        myLog.processData();
    }
}

Output
Jul 24, 2014 2:14:51 PM logger.SimpleLogging processData
INFO: About to start processing data
Jul 24, 2014 2:14:52 PM logger.SimpleLogging processData
INFO: Finished procesing data


static final Logger log = Logger.getLogger("Simple Log");
Above statement creates a logger with the name 'Simple Log'. If a logger with the name 'Simple Log' exist already, then the existed logger is returned.

log.info("About to start processing data");
Above statement logs the information message. By default, the information messages are logged to console. So that only you are seeing the logged messages in console.


Prevoius                                                 Next                                                 Home

Java Logging



Logging is the process of writing log messages during the execution of a program. Logging place a vital role while debugging an Application. Logging using java.util.logging package is depicted in above figure. Logging is done using Logger instance. Loggers get the data and make them in the form of LogRecord and send them to the Handlers. Handlers written the data to external world like consoles, files, network sockets etc.,

As shown in the figure Filters are associated with both loggers and handlers. Filters decide whether to forward or discard particular log record.

Handlers use formatters to format the data. A Formatter provides support for formatting LogRecords. SimpleFormatter, XMLFormatter are provided by java.util.logging package.



Prevoius                                                 Next                                                 Home

Friday, 1 August 2014

convert character to string in java

There are many ways to convert a character to a string.

Example
public class CharToString {
   public static void main(String args[]){
       char ch = 'a';
       
       String str1 = String.valueOf(ch);
       String str2 = Character.toString(ch);
       String str3 = "" + ch;
       String str4 = new String(new char[]{ch});
   } 
}



                                                             Home

Download file from Internet using Java

import java.nio.channels.*;
import java.net.*;
import java.io.*;

public class DownloadFile {
    public static void main(String args[]) throws Exception{
        URL website = new URL("http://courses.coreservlets.com/Course-Materials/pdf/struts/01-Struts-Intro.pdf");
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        FileOutputStream fos = new FileOutputStream("structs.pdf");
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
        rbc.close();
    }
}


                                                             Home

Get key from value in HashMap


import java.util.*;

public class GetKeyFromValue {
    public static void main(String args[]){
        HashMap<Integer, String> map = new HashMap<> ();
        
        /* Add Elements to map*/
        map.put(1, "Krishna");
        map.put(2, "Arjun");
        map.put(3, "Murali");
        map.put(4, "Krishna");
        map.put(5, "Joel");
        
        Set<HashMap.Entry<Integer, String>> set = map.entrySet();
        Iterator<HashMap.Entry<Integer, String>> iter = set.iterator();
        
        String searchVal = "Krishna";
        
        System.out.println("Keys with respect to value " + searchVal);
        while(iter.hasNext()){
           HashMap.Entry entry = iter.next();
           if(entry.getValue().equals(searchVal)){
               System.out.println(entry.getKey());
           }
        }
    }
}

Output
Keys with respect to value Krishna
1
4




                                                             Home