Sometimes in our application we need to log different messages like info,warning,error etc.Here i have given a way how we can use it in our application.
Following 'Log' class creates different log files taking different logger value by input and it also maintains the directory structure of log files according to the value of 'path' passed to the constructor of 'Log' class.For example, if we 'll pass a parameter 'utils.Example',it will create a file 'logs/utils/Example.log' in the current directory.
Note:First it checks for the directory 'logs/utils' is present or not if it is not present it creates the directory.
//Log.java
Note: Everytime you run the 'utils/Example.java' you 'll get a fresh file with new content.
//Content of 'logs/utils/Example.log' after running 'utils/Example.java'
Dec 6, 2011 6:37:33 PM utils.Log loggerINFO
INFO: Doing division by zero
Dec 6, 2011 6:37:33 PM utils.Log loggerWARN
WARNING: May get ArithmeticException
Dec 6, 2011 6:37:33 PM utils.Log loggerERROR
SEVERE: / by zero
Following 'Log' class creates different log files taking different logger value by input and it also maintains the directory structure of log files according to the value of 'path' passed to the constructor of 'Log' class.For example, if we 'll pass a parameter 'utils.Example',it will create a file 'logs/utils/Example.log' in the current directory.
Note:First it checks for the directory 'logs/utils' is present or not if it is not present it creates the directory.
//Log.java
- package utils;
- import java.io.File;
- import java.io.IOException;
- import java.util.logging.FileHandler;
- import java.util.logging.Logger;
- import java.util.logging.SimpleFormatter;
- public class Log {
- try {
- if(f.exists()==false){
- f.mkdirs();
- }
- logger.addHandler(handler);
- e.printStackTrace();
- }
- }
- logger.info(msg);
- }
- logger.warning(msg);
- }
- logger.severe(msg);
- }
- }
- package utils;
- import static utils.Log.loggerINFO;
- import static utils.Log.loggerWARN;
- import static utils.Log.loggerERROR;
- public class Example {
- public Example() {
- Log.createLog(this.getClass().getName());
- }
- public void method1(){
- loggerINFO("Doing division by zero");//Log an INFO message
- loggerWARN("May get ArithmeticException");//Log a WARNING message
- try {
- int i = 20/0;
- loggerERROR(e.getMessage());//Log a SEVERE message
- }
- }
- new Example().method1();
- }
- }
Note: Everytime you run the 'utils/Example.java' you 'll get a fresh file with new content.
//Content of 'logs/utils/Example.log' after running 'utils/Example.java'
Dec 6, 2011 6:37:33 PM utils.Log loggerINFO
INFO: Doing division by zero
Dec 6, 2011 6:37:33 PM utils.Log loggerWARN
WARNING: May get ArithmeticException
Dec 6, 2011 6:37:33 PM utils.Log loggerERROR
SEVERE: / by zero
No comments:
Post a Comment