Friday, April 10, 2015

Logging in Java


Logging can be defined as a way to record or see desired messages in some form during the execution of code. It help us in seeing and understanding the execution flow of of our programs or application.At some point of time every serious code base have it.
There are lot of ways in which logging can be achieved in java.We have various  readymade framework which we can use for logging.
Since there are so many options available , some time folks get confused what is what..So i thought of putting some clarity ..
we  mostly use  following logging frameworks - log4j, commons-logging ,java logging ,slf4, avlon logging , and i guess they are most popular too..
As a matter of fact, Sun java itself provides logging package.
It was introduced in jdk 1.4. we have java.util.logging package.
very simple usage
Logger logger = Logger.getLogger("xvz.com");
logger.info("This is java Util logging");
Thats it!!..if you run above piece of code (obviously putting it in main method) it will print "This is java Util logging" on the console.
There are many configuration parameters or properties which can be set in 2 ways -
1. Through java code.
2. Through property  file.(Either we can have $java_home/lib/logging.properties - then we don't have to do any initialization in the code , Or we can have property file with logger configuration - it needs to be initialized through code.)
Most of time we just need to configure just two things - log level and location of the property file
Adding this to above code will help us in achieving this

FileHandler handler = new FileHandler("c:\\drive1\\demo.log");
logger.addHandler(handler);
logger.setLevel(Level.ALL);
handler.setFormatter(new SimpleFormatter())


However it is advisable to put configuration stuff in property file - outside the code base as it help it changing the logging configuration without changing the code base.
Now lets dig bit deeper into logging package understand some main basic concepts..
Log Levels - In almost all logging frameworks we have different log levels and each framework have its own naming conventions for these log levels.Different Log Levels helps us in classifying our log messages (msg text which we want to present in our log file).For Example we can have different log level for error messages and different log level for common messages. Now once our program is up and running in production environment , we probably don't need to log common messages as it will unnecessarily consume system resources , but however we would like to log error messages, as it will help us in figuring out the problem later.So to handle above use case we have different log levels .they indicate how important the log message is and we have a hierarchy of log message ranked as per importance of messages.
We have have following log levels in order of severity or importance.

SEVERE (most important)
WARNING
INFO
CONFIG
FINE
FINER
FINEST (least important)

We can set the log levels only among the above mentioned seven level. Let us see how it works..
If log level is set as info
logger.setLevel(Level.info)
and if we log two statements,,
logger.info("This is info");
logger.finest("This is finest");
then only "this is info" is printed. However if we have log level as finest
logger.setLevel(Level.finest);
Then both "this is info" and "This is finest" is printed. the thing which we need to understand here is that ,whatever log level we set , we will have log statements from that level , as well as the level above it.Lowest the log level , we will have more log statements in our log file.
If logger is used intelligently , then it becomes very easy to debug and fix the errors.









Thursday, April 18, 2013

Monitoring Apache HTTPD using mod_stats module


Last month i came across very useful monitoring module for apache HTTPD called - mod_stats Thought of sharing it across.
Once this module is configured and enabled , user can monitor httpd remotely via browser .Using this tool we can get insights on
CPU usage,
memory consumed ,
no of threads,
throughput
total data transfer and other important stats related to HTTPD ,on the real time basis..
Very simple and easy to use - steps as follows..

Steps to Configure it

1. Copy "mod_status.so" file  in " /usr/lib/httpd/modules/"

2. Copy following lines in httpd.conf at the last.

     LoadModule status_module /usr/lib/httpd/modules/mod_status.so
     ExtendedStatus On 
     <Location /server-status> 
     SetHandler server-status 
     Order Deny,Allow 
     Deny from all 
     Allow from IP 
     </Location>


Note : IP in above snippet is the ip of the machine from which you want to access the server status page.HTTPD will white list this IP for monitoring page access.

3. Restart HTTPD


4 Now launch https://<ip>/server-status?refresh=1
   refresh=1 param refreshes this page on auto mode every 1 second

    monitoring page will look like ths diplaying all the vital stats about the HTTPD server.

  




Saturday, March 9, 2013

All About Ant...


I felt like doing a small write up ANT build tool..
ANT - acronym for "Another Neat Tool" is a java based build tool used to compile , assemble  or package source code in a neat presentable way or in simply it is used to build jars and wars.
How it works...
It reads instruction steps, one by one from a XML file and execute them sequentially. These instruction steps are define in terms of some set of keywords (user friendly and easy to understand)
and have specific meaning attached to it e.g.  "property" keyword means name of the variable or "depends" keyword means that something depends on something.
Now let’s get 
started and create a small sample.
First download Ant installable files(zip or tar) from apache ant site.Apache Ant
Since we use ant to build java projects so it is assumed that java is already installed in the system, if java is not there then first download JDK from oracle website and then continue with the ANT setup.
After downloading, unzip the ant folder to any directory (let say in Windows it can be C:\apache-ant-1.8.4 and for Linux it can be /opt/apache-ant-1.8.4) now it’s recommended to set
 "ANT_HOME" environment variable in OS variables and append ANT_HOME/bin; in the existing system path.
In windows go to Environment variable add new variable "ANT_HOME" and set "C:\apache-ant-1.8.4" in value. Now select path from the list of variable and edit its value (at the end add ANT_HOME/bin).
So this will make your ant setup complete. You can go to command prompt ant type ant -version
You will see the version of ant. In case ant is not successfully installed, you will see command not found error.
So now you are ready to dive in. We will create one sample project first and see how ant works.
Let’s create one directory in C drive called sample, this is our working dir.
Need to mention that when we create any java project or write any code, then it is recommended (and looks neat also) to have stuff organized in following directory structure.

  1. src - dir for keeping source code java classes.
  2. build - dir for keeping compiled classes.
  3. lib - dir for keeping dependency

So let us now create above 3 directories in our “sample” dir.
In our src directory put one small java file -  say that prints "hello world"
Now next step is to create build file. Build file is nothing but the above mentioned XML file which ANT will use to read instructions and properties.
First line of the xml file will be
<?xml version="1.0"?>
Which is nothing but just a xml declaration telling which version of xml is being used.
Next is the root element called “project” having 3 basic and mandatory attributes - name , default and basedir.
<project name="test" default="compile" basedir=".">
So first attribute "name" is the name of the project can be anything whatever you feel like.
Next is the default target. Target is nothing but the one modular task that ant performs in one go. Generally one build process can be divided into different smaller modular task
like checking out of latest source code from repository can be termed as one task , deleting and creating directory can be termed as init task or target.
So we can have multiple task or target in a project and these can be latter on weaved together to form one combined task. One target can be composed of single or multiple atomic task.
Further we have 5 attributes attached to target which tell different things about the target.
They are as follows

  1. name- this is a mandatory attribute telling name of the project.
  2. depends -if this target depends on some other target or targets then we need to give it here can be comma separated.
  3. description - again optional
  4. if- this is required if execution of this target depends on some condition.
  5. unless- Optional parameter that adds this target to the dependency list of the specified Extension Point.Extension point is similar to target ,but nothing to execute.

Third attribute is the basedir and every path in build process is relative to this directory.
Now after root tag we can have target tags or variable tags in build xml.
We can define variables in our xml so that they can be used in different targets..say we define our build dir name , and we can use it throughout our xml..they are defined as
<property name ="build" value="build">
and this build variable can be accessed as ${build}.
One more way to define properties is is to define them in a build.property file and add this build.property file in the build.xml (<property file="build.properties"/>)
now lets create one target or modular task.
lets create target called "init"
<target name = "init">
<mkdir dir="${build}"/>
</target>

Now  this init target or modular task is composed of one atomic task which is "mkdir" .now these atomic task have list of predefined attributes or we can say that they are like ant defined functions, we invoke them just by writing names and passing parameters (parameters are passed by giving attributes).

So now our build.xml looks like
<?xml version="1.0"?>
<project name="sample" default="init" basedir=".">
<property name="build" value="build"/>
<target name="init">
<mkdir dir ="${build}" />
</target>
</project>
now if we issue following command
ant , it will create a build dir by executing "init" target.
now for compiling your source code you can have
<javac srcdir="src" destdir="${build}"/>
and for running the Test.java
<java classname="Test"  classpath="${build}"/>
So full list of task can be accessed at Ant Task .