Java Logger API: Creating log in custom format (e.g. CSV format, HTML format)
Java logger API provides built-in support to log error/warning messages. The default format of logging is “simple text format” (java.util.logging.SimpleFormatter) and “XML format” (java.util.logging.XMLFormatter).
However, the logging can be done in any format by creating custom formatter. Following are some simple step to create a custom formatter.
1. Extend the abstract class java.util.logging.Formatter and use following methods:
a) abstract String
format(LogRecord record)
- Abstract class, must be overridden.
- Format the given log record and return the formatted string.
- The java.util.logging.LogRecord object contains all the logging data; like log level, time, source class/method names, thread id/name etc.
b) String
formatMessage(LogRecord record)
: Localize and format the message string from a log record.
- Localize and format the message string from a log record. This method is provided as a convenience for Formatter subclasses to use when they are performing formatting.
-
Implementation is optional. Should be called from the “format” method.
c)
String getHead(Handler h)
-
Return the header string for a set of formatted records.
-
The Handler object connects to the channel/stream/media; over which the log will be written.
-
Not required an explicit call. Automatically called when the handler using this formatter is created.
-
Implementation is optional. Default implementation returns empty string.
d)
String getTail(Handler h)
-
Return the tail string for a set of formatted records.
-
The Handler object connects to the channel/stream/media; over which the log will be written.
-
Not required an explicit call. Automatically called when the handler using this formatter is closed.
-
Implementation is optional. Default implementation returns empty string.
-------------------------------------------------------------------------
Source code example (Tested on Java 5)
-------------------------------------------------------------------------
package com.gyani;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
//This custom formatter formats parts of a log record to a single line
class CustomHtmlFormatter extends Formatter
{
// This method is called for every log records
public String format(LogRecord rec)
{
StringBuffer buffer = new StringBuffer(1000);
// Bold any levels >= WARNING
buffer.append("");
buffer.append("");
if (rec.getLevel().intValue() >= Level.WARNING.intValue())
{
buffer.append("");
buffer.append(rec.getLevel());
buffer.append("");
} else
{
buffer.append(rec.getLevel());
}
buffer.append("");
buffer.append("");
buffer.append(calcDate(rec.getMillis()));
buffer.append(' ');
buffer.append(formatMessage(rec));
buffer.append('\n');
buffer.append("");
buffer.append("\n");
return buffer.toString();
}
private String calcDate(long millisecs)
{
SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");
Date resultdate = new Date(millisecs);
return date_format.format(resultdate);
}
// This method is called just after the handler using this
// formatter is created
public String getHead(Handler h)
{
return "\n\n" + (new Date()) + "\n\n\n\n"
+ "\n " + "
Time | Log Message |
\n"; } // This method is called just after the handler using this // formatter is closed public String getTail(Handler h) { return "
\n
\n\n";
}
public String formatMessage(LogRecord record){
return ".......Hello Gyani....";
}
}
class MyLogger {
static private FileHandler fileTxt;
static private SimpleFormatter formatterTxt;
static private FileHandler fileHTML;
static private Formatter formatterHTML;
static public void setup(Logger logger) throws IOException {
// Create Logger
logger.setLevel(Level.INFO);
fileTxt = new FileHandler("C:\\Gyani\\Logging.txt");
fileHTML = new FileHandler("C:\\Gyani\\Logging.html");
// Create txt Formatter
formatterTxt = new SimpleFormatter();
fileTxt.setFormatter(formatterTxt);
logger.addHandler(fileTxt);
// Create HTML Formatter
formatterHTML = new CustomHtmlFormatter();
fileHTML.setFormatter(formatterHTML);
logger.addHandler(fileHTML);
}
}
public class UseLogger {
// Always use the classname, this way you can refactor
private final static Logger LOGGER = Logger.getLogger(UseLogger.class
.getName());
public UseLogger(){
try {
MyLogger.setup(LOGGER);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Problems with creating the log files");
}
}
public void writeLog() {
// Set the LogLevel to Severe, only severe Messages will be written
LOGGER.setLevel(Level.SEVERE);
LOGGER.severe("Info Log");
LOGGER.warning("Info Log");
LOGGER.info("Info Log");
LOGGER.finest("Really not important");
// Set the LogLevel to Info, severe, warning and info will be written
// Finest is still not written
LOGGER.setLevel(Level.INFO);
LOGGER.severe("Info Log");
LOGGER.warning("Info Log");
LOGGER.info("Info Log");
LOGGER.finest("Really not important");
}
public static void main(String[] args) {
UseLogger logger = new UseLogger();
logger.writeLog();
}
}
-----------------------------------------------------------------------------
Contents are compiled from different resources. Respective copyrights are acknowledged.