For big applications log is very important thing. Using these logs we can detect cause of problem. We can determine the place where problem occurred. For big applications it is necessary to store that log in one of the file. In order to facilitate this java provides Logger class.
This logger class is very easy to use. It allow you to create files in different formats like xml files, simple files etc. This logger class stores lot of information like time stamp, class name, method name and severity of problem.
Here I am giving very simple example one for simple file and another for xml file.
Create simple log file:
Try to execute following code and you will get log file.
Code:
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class Test
{
FileHandler fileHandler;
Logger logger;
public Test()
{
try
{
fileHandler = new FileHandler("test.log");
logger = Logger.getLogger("log_file");
logger.addHandler(fileHandler);
fileHandler.setFormatter(new SimpleFormatter());
}
catch(Exception e)
{
System.out.print("Exception : " + e);
}
}
public static void main(String[] args)
{
Test t = new Test();
t.testingMethod();
t.anotherMethod();
}
private void testingMethod()
{
try
{
logger.warning("See what is happening.");
logger.info("See again");
logger.severe("It is problem");
}
catch(Exception e)
{
System.out.print("Exception : " + e);
}
}
private void anotherMethod()
{
try
{
logger.addHandler(fileHandler);
fileHandler.setFormatter(new SimpleFormatter());
logger.warning("Test");
logger.info("Test");
logger.severe("Test");
}
catch(Exception e)
{
System.out.print("Exception : " + e);
}
}
}
Using this mechanism you can add logs to your applications.
No comments:
Post a Comment