In the earlier article, we have seen how to create logs. However, that was in html format.
I have been recently given task of creating logs in text format – just wanted to share this with you. The pre-requisite jars will be same as mentioned earlier and it will be a pretty simple task.
The below simple code logs the information messages, debug messages and the error messages.
Logger API : http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Logger.html
There is one log4jconfig.properties which contains the logger file properties. So we will use another java class to access the properties file.
The entries which I have used in the log4jconfig.properties file are:
log4j.rootLogger=DEBUG, file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=logger.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
Log4Logger.java
/*
* Log4Logger.java
* Snehanshu Chatterjee
*/
import java.util.Properties;
import org.apache.log4j.Category;
import org.apache.log4j.PropertyConfigurator;
public class Log4Logger extends org.apache.log4j.Logger {
static Category category=null;
/** Creates a new instance of Log4Logger */
public Log4Logger(String name) {
super(name);
}
/** static block for getting the file path scheduler.properties and reads the properties file*/
static{
try{
Properties logProp=new Properties();
String fName = new String("./config/log4jconfig.properties");
try {
PropertyConfigurator.configure(fName);
} catch(Exception e) {
System.out.println(e.getMessage());
}
} catch(Exception e){
System.out.println(e.getMessage());
}
}
public static Category returnLogger(String name) {
category= Log4Logger.getLogger(name);
return category;
}
}
The below code which actually logs any information.
LoggerDemo.java
/*
LoggerTest.java
Snehanshu Chatterjee
*/
import org.apache.log4j.Category;
public class LoggerTest {
static Category LOGGGER = Log4Logger.returnLogger(LoggerTest.class.getName());
public static void main(String args[]) {
LOGGGER.debug("Debug message");
LOGGGER.info("Info message");
LOGGGER.error("Error message");
LOGGGER.fatal("Fatal message");
LOGGGER.warn("Warning message");
}
}
Output in the logger file
2011-06-23 19:38:50,470 [main] DEBUG test.LoggerTest - Debug message
2011-06-23 19:38:50,470 [main] INFO test.LoggerTest - Info message
2011-06-23 19:38:50,470 [main] ERROR test.LoggerTest - Error message
2011-06-23 19:38:50,470 [main] FATAL test.LoggerTest - Fatal message
2011-06-23 19:38:50,470 [main] WARN test.LoggerTest - Warning message
No comments:
Post a Comment