1. Logging Technology
Java Log file is one of the important and most usable technologies for java development. Most of the application maintains its’ own log for future maintenance and trouble shooting. Logging is a good debugging technique in software development.
For example, you can log all exceptions to find out quickly what wrong with the code. Debugging statement-wise can be tedious as you know. Besides, looking up the log file helps in identifying even the most elusive bugs.
You can implement logging functionality in different ways. Here I am trying to explain main two way logging implementation technique.
First, the most popular technique is use third party logging implementation in your application. And second is java provides log classed to implement logging technology with jdk1.4 itself.
2. Log4j Logging Technology
First, the most popular technique is use third party logging implementation in your application. There are many third parties logging jar file available in market. Apache log4j is the most popular and used logger technology. It is very easy to use and configurable for application development.
2.1. Log4j Logging (normal)
This is the most popular and used technology for logging implementation. It is freeware and completely configurable. Only three steps is enough to configure log4j implementation.
Steps are:-
1. Downsload log4j-1.2.15.jar file. Set class path log4j file. Clieck here to download log4j-1.2.15.jar http://www.findjar.com/jar/log4j/jars/log4j-1.2.15.jar.html .
2. Create log4j.properties file. Configure logger appender, log file path, log message format and log message level.
3. Now logger configuration ready and use logger in your class file.
2.1.1. Directory structure
The directory structure of the example is shown below:-
2.1.2. File log4j.properties
#===========================================
# logger appender level
# DEBUG=> logger level for Console
# CA=> log messages in Console;
# FILE=> log messages in File
#===========================================
log4j.rootLogger=DEBUG,CA,FILE
#===========================================
# File log Appender Configuration.
#This is required if you want to write log message in file.
#===========================================
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=example.log
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
#============================================
# ConsoleAppender Configuration.
#This is required if you want to write log message in file.
#============================================
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
#============================================
#Package Level log Appender.Add this poetion if need package level log.
#This is not mandatory. If it is required then configure this portion.
#log4j.logger.
#log4j.appender.
#=============================================
log4j.appender.JavaLog4jExampleFileAppender=org.apache.log4j.FileAppender
log4j.appender.JavaLog4jExampleFileAppender.File=example.log
log4j.appender.JavaLog4jExampleFileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.JavaLog4jExampleFileAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
log4j.logger.paria.league.java.log4j.example=WARN,JavaLog4jExampleFileAppender
2.1.3. log4j.propeties screen shoot.
2.1.4. Java class file for logger
package paria.league.java.log4j.example;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class JavaLog4jExample {
static Logger logger = Logger.getLogger(JavaLog4jExample.class);
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
logger.debug("Sample debug message");
logger.info("Sample info message");
logger.warn("Sample warn message");
logger.error("Sample error message");
logger.fatal("Sample fatal message");
}
}
2.1.5. Log message java class screen shoot.
2.2. Log4j Rolling File Appender (size wise)
Logger messages will be append in the log file. If it is continuously happened log file will be increase. If you need to archive the log file according to the file size limit then need to configure log file appender as RollingFileAppender. When file size exceed more than configured file size then new log file will be created and old file will be archived. This rolling appender file is used for file size limit archive.
2.2.1. File log4j.properties
#=============================================
# BEGIN APPENDER: ROLLING FILE APPENDER (rolling)
log4j.rootLogger=DEBUG, rolling
# first: type of appender (fully qualified class name)
log4j.appender.rolling=org.apache.log4j.RollingFileAppender
# second: Any configuration information needed for that appender.
# Many appenders require a layout.
log4j.appender.rolling.File=example.log
log4j.appender.rolling.MaxFileSize=1KB
# Keep one backup file
log4j.appender.rolling.MaxBackupIndex=1
log4j.appender.rolling.layout=org.apache.log4j.PatternLayout
log4j.appender.rolling.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
# END APPENDER: ROLLING FILE APPENDER (rolling)
#==========================================
According to log4j file configuration, log file message will be append in the example.log file. When example.log file size will be exceed 1KB size then new example.log file will be archived as example.log.1 and another new example.log file will be created.
2.2.2. Directory structure
The directory structure with rolling archived file example (size wise) is shown below.
2.3. Log4j Rolling File Appender (time wise)
Logger messages will be append in the log file. If it is continuously happened log file will be increase. If you need to archive the log file according to the file time limit then need to configure log file appender as DaillyRollingFileAppender. When time limit exceed more than configured time span then new log file will be created and old file will be archived. This rolling appender file is used for file time limit archive.
2.3.1. File log4j.properties
#================================================
# BEGIN APPENDER: DAILY ROLLING FILE APPENDER (rolling)
log4j.rootLogger=DEBUG, R
#log4j.properties file create an appender of type DailyRollingFileAppender:
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
#define the date pattern which will be used in naming the log files:
log4j.appender.R.DatePattern='-'yyyy-MM-dd-hh-mm'.log'
#define the path of your log files:
log4j.appender.R.File=example.log
#and configure how logs should appear inside the file:
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
# END APPENDER: DAILY ROLLING FILE APPENDER (rolling)
#============================================
According to log4j file configuration, log file message will be append in the example.log file. Here configured for every minute log file will be archived. After one minute example.log file will be archived as example.log-2011-09-22-15-01.log and another new example.log file will be created. If you need to customize file name then provide log4j.appender.R.DatePattern and log4j.appender.R.File properties pattern.
2.3.2. Directory structure
The directory structure with rolling archived file example (time wise) is shown below.
2.3.3. Example Custom Description
If you want archive file name pattern like FileName-yyyy-MM-dd.log i.e. example.log as example-2011-09-22.log then provide log4j.appender.R.DatePattern and log4j.appender.R.File properties pattern as bellow:-
log4j.appender.R.DatePattern='-'yyyy-MM-dd'.log'
log4j.appender.R.File=example
3. Java Log Technology
Java provides log classed to implement logging technology with jdk1.4 itself. Sometimes third party log is not suitable for the application then java log is very useful. Not only third party issue, you can use java log as logger technology in your application. Here you have to write your own code for it.
3.1. Java Log Rolling File (time & size wise)
Here this log file implements logger implementation. This java class completely java based class, not jar file is required. This is simple basic log implementation class. I provide default log file name size etc, if you need flexibility please implement properties file for configuration of those hard code valued for your application.
3.1.1. Java log file class.
Copy this class in your application and use log implementation in your application. If you need more customize please customize. Here all customize parameter provides for logging level, date, file naming convention etc.
package paria.league.java.log.example;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* This class implements java log file for date and size wise wise rolling file. It will create new log file every minute. If log file size increase more than.1KB then it will create new file with same time stamp with sequence number. As Example, log file name javaLog_09-23-2011-00-57_0.log (javaLog_
*
* @author aparia Sep-09,2011
* @Copywrite paria league
*/
public class JavaLogExample {
private static Logger logger = Logger.getLogger("JavaLogExample");
private static String logFileName = null;
private static int logFileLimit = 0;
private static FileHandler logFileHandler;
/**
* This static bloc set the file name file size and file name patter with time stamp format.
*
* @author aparia Sep-09,2011
*/
static {
try {
logFileName = "javaLog";
logFileLimit = 1024;
SimpleDateFormat DateTime =
new SimpleDateFormat("MM-dd-yyyy-HH-mm");
DateTime.setTimeZone(TimeZone.getTimeZone("EST"));
String now = DateTime.format(new Date());
logFileHandler =
new FileHandler(logFileName + "_" + now.toString()
+ "_%g.log", logFileLimit, 200, true);
} catch (SecurityException e) {
} catch (IOException e) {
} catch (Exception e) {
}
}
/**
* Private default constructor
*
* @author aparia Sep-09,2011
*/
private JavaLogExample() {
}
/**
* This method returns JavaLogExample instance.
*
* @author aparia Sep-09,2011
* @return JavaLogExample
*/
public static JavaLogExample getLogger() {
return new JavaLogExample();
}
/**
* This method format logger message format and write message in log file permanently. Here message argument is for log messages and level for logging level.
* Here this level is not implemented. If you want to implement logging level write a java class and provide the logging level as integer value.
*
* @author aparia Sep-09,2011
* @param message
* @param level
*/
private static void append(String message, int level) {
final String logMsg = message;
logFileHandler.setFormatter(new Formatter() {
public String format(LogRecord rec) {
DateFormat dateFormat = new SimpleDateFormat(
"MM.dd.yyyy hh:mm:ss a zzz");
Date date = new Date();
String sLevel = "1";
StringBuffer buf = new StringBuffer(1000);
buf.append("[" + dateFormat.format(date) + "]");
buf.append("[" + sLevel + "]");
buf.append(" - ");
buf.append(logMsg);
buf.append("\r\n");
String logFormatStr = buf.toString();
return logFormatStr;
}
});
logger.addHandler(logFileHandler);
logger.log(Level.INFO, message);
}
/**
* This method logged debug message
*
* @author aparia Sep-09,2011
* @param message
*/
public void debug(String message) {
JavaLogExample.append(message, 0);
}
/**
* This method logged info message
*
* @author aparia Sep-09,2011
* @param message
*/
public void info(String message) {
JavaLogExample.append(message, 1);
}
/**
* This method warning debug message
*
* @author aparia Sep-09,2011
* @param message
*/
public void warn(String message) {
JavaLogExample.append(message, 2);
}
/**
* This method logged error message
*
* @author aparia Sep-09,2011
* @param message
*/
public void error(String message) {
JavaLogExample.append(message, 3);
}
}
3.1.2. Java log test class.
This java class for test java log implementation. Run this class to test logger messages. It will create java log file as javaLog_09-23-2011-00-30_0.log and last sequence will be increate according to the log file size in the specific time frame. If javaLog_09-23-2011-00-30_0.log file size increased more than 1KB then archive file name will be javaLog_09-23-2011-00-30_1.log. If you run again after one minute then it will create new log file like javaLog_09-23-2011-00-31_0.log or javaLog_09-23-2011-00-31_1.log according to the file size.
package paria.league.java.log.example;
/**
* This java for test java log implementation
* @author aparia Sep-232,2011
*
*/
public class JavLogTestMain {
/**
* java logger file instance
*/
private static final JavaLogExample logger= JavaLogExample.getLogger();
/**
* Main method to run and log messages
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
logger.debug("debug mation test");
logger.info("infor mation test");
logger.warn("warning mation test");
logger.error("error mation test");
}
}
3.1.3. Directory structure
The directory structure with rolling archived file example (time wise and size wise) is shown below.
4. Log Technology project code
download log4j and java log scorce code click here
No comments:
Post a Comment