Difference between revisions of "Java: Logging API"

From OnnoWiki
Jump to navigation Jump to search
(New page: Java Logging This article describes how to use the Logging API in Java programs. It includes an example for creating a HTML logger. Table of Contents 1. Overview 1.1. Logging in Ja...)
 
Line 1: Line 1:
Java Logging
+
Sumber: http://www.vogella.de/articles/Logging/article.html
  
This article describes how to use the Logging API in Java programs. It includes an example for creating a HTML logger.
+
Tulisan ini menjelaskan bagaimana cara menggunakan API di program Java. Termasuk cara membuat logger HTML.
  
Table of Contents
 
 
1. Overview
 
 
    1.1. Logging in Java
 
    1.2. Create a logger
 
    1.3. Level
 
    1.4. Handler
 
    1.5. Formatter
 
    1.6. Log Manager
 
    1.7. Best Practices
 
 
2. Example
 
3. Thank you
 
4. Questions and Discussion
 
5. Links and Literature
 
  
 
1. Overview
 
1. Overview
Line 30: Line 14:
 
To create a logger in your Java coding.
 
To create a logger in your Java coding.
  
+
import java.util.logging.Logger;
import java.util.logging.Logger;
+
 
+
private final static Logger LOGGER = Logger.getLogger(MyClass.class .getName());
private final static Logger LOGGER = Logger.getLogger(MyClass.class .getName());
 
  
 
 
Line 60: Line 43:
  
 
For example the following will set the logger to level info which means all messages with severe, warning and info will be logged.
 
For example the following will set the logger to level info which means all messages with severe, warning and info will be logged.
 
+
+
LOGGER.setLevel(Level.INFO);
LOGGER.setLevel(Level.INFO);
 
  
 
 
Line 76: Line 58:
 
You have several standard handler, e.g.
 
You have several standard handler, e.g.
  
    ConsoleHandler: Write the log message to console
+
ConsoleHandler: Write the log message to console
 +
 +
FileHandler: Writes the log message to file
  
    FileHandler: Writes the log message to file
+
Log Levels INFO and higher will be automatically written to the console.
  
Log Levels INFO and higher will be automatically written to the console.
 
 
1.5. Formatter
 
1.5. Formatter
  
Line 87: Line 70:
 
Available formatter
 
Available formatter
  
    SimpleFormatter Generate all messages as text
+
SimpleFormatter Generate all messages as text
 
+
    XMLFormatter Generates XML output for the log messages
+
XMLFormatter Generates XML output for the log messages
  
 
You can also build your own formatter. The following is an example of a formatter which will use create HTML output.
 
You can also build your own formatter. The following is an example of a formatter which will use create HTML output.
  
+
package logging;
package logging;
+
 
+
import java.text.SimpleDateFormat;
import java.text.SimpleDateFormat;
+
import java.util.Date;
import java.util.Date;
+
import java.util.logging.Formatter;
import java.util.logging.Formatter;
+
import java.util.logging.Handler;
import java.util.logging.Handler;
+
import java.util.logging.Level;
import java.util.logging.Level;
+
import java.util.logging.LogRecord;
import java.util.logging.LogRecord;
+
 
+
//This custom formatter formats parts of a log record to a single line
//This custom formatter formats parts of a log record to a single line
+
class MyHtmlFormatter extends Formatter
class MyHtmlFormatter extends Formatter
+
{
{
+
// This method is called for every log records
// This method is called for every log records
+
public String format(LogRecord rec)
public String format(LogRecord rec)
+
{
{
+
StringBuffer buf = new StringBuffer(1000);
StringBuffer buf = new StringBuffer(1000);
+
// Bold any levels >= WARNING
// Bold any levels >= WARNING
+
buf.append("<tr>");
buf.append("<tr>");
+
buf.append("<td>");
buf.append("<td>");
+
 
+
if (rec.getLevel().intValue() >= Level.WARNING.intValue())
if (rec.getLevel().intValue() >= Level.WARNING.intValue())
+
{
{
+
buf.append("<b>");
buf.append("<b>");
+
buf.append(rec.getLevel());
buf.append(rec.getLevel());
+
buf.append("</b>");
buf.append("</b>");
+
} else
} else
+
{
{
+
buf.append(rec.getLevel());
buf.append(rec.getLevel());
+
}
}
+
buf.append("</td>");
buf.append("</td>");
+
buf.append("<td>");
buf.append("<td>");
+
buf.append(calcDate(rec.getMillis()));
buf.append(calcDate(rec.getMillis()));
+
buf.append(' ');
buf.append(' ');
+
buf.append(formatMessage(rec));
buf.append(formatMessage(rec));
+
buf.append('\n');
buf.append('\n');
+
buf.append("<td>");
buf.append("<td>");
+
buf.append("</tr>\n");
buf.append("</tr>\n");
+
return buf.toString();
return buf.toString();
+
}
}
+
 
+
private String calcDate(long millisecs)
private String calcDate(long millisecs)
+
{
{
+
SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");
SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");
+
Date resultdate = new Date(millisecs);
Date resultdate = new Date(millisecs);
+
return date_format.format(resultdate);
return date_format.format(resultdate);
+
}
}
+
 
+
// This method is called just after the handler using this
// This method is called just after the handler using this
+
// formatter is created
// formatter is created
+
public String getHead(Handler h)
public String getHead(Handler h)
+
{
{
+
return "<HTML>\n<HEAD>\n" + (new Date()) + "\n</HEAD>\n<BODY>\n<PRE>\n"
return "<HTML>\n<HEAD>\n" + (new Date()) + "\n</HEAD>\n<BODY>\n<PRE>\n"
+
+ "<table border>\n  "
+ "<table border>\n  "
+
+ "<tr><th>Time</th><th>Log Message</th></tr>\n";
+ "<tr><th>Time</th><th>Log Message</th></tr>\n";
+
}
}
+
 
+
// This method is called just after the handler using this
// This method is called just after the handler using this
+
// formatter is closed
// formatter is closed
+
public String getTail(Handler h)
public String getTail(Handler h)
+
{
{
+
return "</table>\n  </PRE></BODY>\n</HTML>\n";
return "</table>\n  </PRE></BODY>\n</HTML>\n";
+
}
}
+
}  
}
 
  
 
 
Line 165: Line 147:
  
 
We could set the logging level for a package, or even a set of packages, by calling the LogManager.setLevel(String name, Level level) method. So, for example, we could set the logging level of all loggers "logging" to Level.FINE by making this call:
 
We could set the logging level for a package, or even a set of packages, by calling the LogManager.setLevel(String name, Level level) method. So, for example, we could set the logging level of all loggers "logging" to Level.FINE by making this call:
 
 
 
LogManager.getLogManager().setLevel("logging", Level.FINE)
+
LogManager.getLogManager().setLevel("logging", Level.FINE)
  
 
 
Line 176: Line 157:
  
 
Using the fully qualified class name of your class as the name of your Logger is the approach recommended by the Logging API documentation.
 
Using the fully qualified class name of your class as the name of your Logger is the approach recommended by the Logging API documentation.
 +
 
2. Example
 
2. Example
  
Line 182: Line 164:
 
Create your own formatter.
 
Create your own formatter.
  
+
package logging;
package logging;
+
 
+
import java.text.SimpleDateFormat;
import java.text.SimpleDateFormat;
+
import java.util.Date;
import java.util.Date;
+
import java.util.logging.Formatter;
import java.util.logging.Formatter;
+
import java.util.logging.Handler;
import java.util.logging.Handler;
+
import java.util.logging.Level;
import java.util.logging.Level;
+
import java.util.logging.LogRecord;
import java.util.logging.LogRecord;
+
 
+
//This custom formatter formats parts of a log record to a single line
//This custom formatter formats parts of a log record to a single line
+
class MyHtmlFormatter extends Formatter
class MyHtmlFormatter extends Formatter
+
{
{
+
// This method is called for every log records
// This method is called for every log records
+
public String format(LogRecord rec)
public String format(LogRecord rec)
+
{
{
+
StringBuffer buf = new StringBuffer(1000);
StringBuffer buf = new StringBuffer(1000);
+
// Bold any levels >= WARNING
// Bold any levels >= WARNING
+
buf.append("<tr>");
buf.append("<tr>");
+
buf.append("<td>");
buf.append("<td>");
+
 
+
if (rec.getLevel().intValue() >= Level.WARNING.intValue())
if (rec.getLevel().intValue() >= Level.WARNING.intValue())
+
{
{
+
buf.append("<b>");
buf.append("<b>");
+
buf.append(rec.getLevel());
buf.append(rec.getLevel());
+
buf.append("</b>");
buf.append("</b>");
+
} else
} else
+
{
{
+
buf.append(rec.getLevel());
buf.append(rec.getLevel());
+
}
}
+
buf.append("</td>");
buf.append("</td>");
+
buf.append("<td>");
buf.append("<td>");
+
buf.append(calcDate(rec.getMillis()));
buf.append(calcDate(rec.getMillis()));
+
buf.append(' ');
buf.append(' ');
+
buf.append(formatMessage(rec));
buf.append(formatMessage(rec));
+
buf.append('\n');
buf.append('\n');
+
buf.append("<td>");
buf.append("<td>");
+
buf.append("</tr>\n");
buf.append("</tr>\n");
+
return buf.toString();
return buf.toString();
+
}
}
+
 
+
private String calcDate(long millisecs)
private String calcDate(long millisecs)
+
{
{
+
SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");
SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");
+
Date resultdate = new Date(millisecs);
Date resultdate = new Date(millisecs);
+
return date_format.format(resultdate);
return date_format.format(resultdate);
+
}
}
+
 
+
// This method is called just after the handler using this
// This method is called just after the handler using this
+
// formatter is created
// formatter is created
+
public String getHead(Handler h)
public String getHead(Handler h)
+
{
{
+
return "<HTML>\n<HEAD>\n" + (new Date()) + "\n</HEAD>\n<BODY>\n<PRE>\n"
return "<HTML>\n<HEAD>\n" + (new Date()) + "\n</HEAD>\n<BODY>\n<PRE>\n"
+
+ "<table border>\n  "
+ "<table border>\n  "
+
+ "<tr><th>Time</th><th>Log Message</th></tr>\n";
+ "<tr><th>Time</th><th>Log Message</th></tr>\n";
+
}
}
+
 
+
// This method is called just after the handler using this
// This method is called just after the handler using this
+
// formatter is closed
// formatter is closed
+
public String getTail(Handler h)
public String getTail(Handler h)
+
{
{
+
return "</table>\n  </PRE></BODY>\n</HTML>\n";
return "</table>\n  </PRE></BODY>\n</HTML>\n";
+
}
}
+
}  
}
 
  
 
 
Line 251: Line 232:
 
Initialize the logger.
 
Initialize the logger.
  
+
package logging;
package logging;
+
 
+
import java.io.IOException;
import java.io.IOException;
+
import java.util.logging.FileHandler;
import java.util.logging.FileHandler;
+
import java.util.logging.Formatter;
import java.util.logging.Formatter;
+
import java.util.logging.Level;
import java.util.logging.Level;
+
import java.util.logging.Logger;
import java.util.logging.Logger;
+
import java.util.logging.SimpleFormatter;
import java.util.logging.SimpleFormatter;
+
 
+
public class MyLogger {  
public class MyLogger {
+
static private FileHandler fileTxt;
static private FileHandler fileTxt;
+
static private SimpleFormatter formatterTxt;
static private SimpleFormatter formatterTxt;
+
 
+
static private FileHandler fileHTML;
static private FileHandler fileHTML;
+
static private Formatter formatterHTML;
static private Formatter formatterHTML;
+
 
+
static public void setup() throws IOException {
static public void setup() throws IOException {
+
// Create Logger
// Create Logger
+
Logger logger = Logger.getLogger("");
Logger logger = Logger.getLogger("");
+
logger.setLevel(Level.INFO);
logger.setLevel(Level.INFO);
+
fileTxt = new FileHandler("Logging.txt");
fileTxt = new FileHandler("Logging.txt");
+
fileHTML = new FileHandler("Logging.html");
fileHTML = new FileHandler("Logging.html");
+
 
+
// Create txt Formatter
// Create txt Formatter
+
formatterTxt = new SimpleFormatter();
formatterTxt = new SimpleFormatter();
+
fileTxt.setFormatter(formatterTxt);
fileTxt.setFormatter(formatterTxt);
+
logger.addHandler(fileTxt);
logger.addHandler(fileTxt);
+
 
+
// Create HTML Formatter
// Create HTML Formatter
+
formatterHTML = new MyHtmlFormatter();
formatterHTML = new MyHtmlFormatter();
+
fileHTML.setFormatter(formatterHTML);
fileHTML.setFormatter(formatterHTML);
+
logger.addHandler(fileHTML);
logger.addHandler(fileHTML);
+
}
}
+
}  
}
 
  
 
 
Line 291: Line 271:
 
Use the logger.
 
Use the logger.
  
+
package logging;
package logging;
+
 
+
import java.io.IOException;
import java.io.IOException;
+
import java.util.logging.Level;
import java.util.logging.Level;
+
import java.util.logging.Logger;
import java.util.logging.Logger;
+
 
+
public class UseLogger {
public class UseLogger {
+
// Always use the classname, this way you can refactor
// Always use the classname, this way you can refactor
+
private final static Logger LOGGER = Logger.getLogger(UseLogger.class
private final static Logger LOGGER = Logger.getLogger(UseLogger.class
+
.getName());
.getName());
+
 
+
public void writeLog() {
public void writeLog() {
+
// Set the LogLevel to Severe, only severe Messages will be written
// Set the LogLevel to Severe, only severe Messages will be written
+
LOGGER.setLevel(Level.SEVERE);
LOGGER.setLevel(Level.SEVERE);
+
LOGGER.severe("Info Log");
LOGGER.severe("Info Log");
+
LOGGER.warning("Info Log");
LOGGER.warning("Info Log");
+
LOGGER.info("Info Log");
LOGGER.info("Info Log");
+
LOGGER.finest("Really not important");
LOGGER.finest("Really not important");
+
 
+
// Set the LogLevel to Info, severe, warning and info will be written
// Set the LogLevel to Info, severe, warning and info will be written
+
// Finest is still not written
// Finest is still not written
+
LOGGER.setLevel(Level.INFO);
LOGGER.setLevel(Level.INFO);
+
LOGGER.severe("Info Log");
LOGGER.severe("Info Log");
+
LOGGER.warning("Info Log");
LOGGER.warning("Info Log");
+
LOGGER.info("Info Log");
LOGGER.info("Info Log");
+
LOGGER.finest("Really not important");
LOGGER.finest("Really not important");
+
}
}
+
 
+
public static void main(String[] args) {
public static void main(String[] args) {
+
UseLogger logger = new UseLogger();
UseLogger logger = new UseLogger();
+
try {
try {
+
MyLogger.setup();
MyLogger.setup();
+
} catch (IOException e) {
} catch (IOException e) {
+
e.printStackTrace();
e.printStackTrace();
+
throw new RuntimeException("Problems with creating the log files");
throw new RuntimeException("Problems with creating the log files");
+
}
}
+
logger.writeLog();
logger.writeLog();
+
}
}
+
}
}
 
  
 
 

Revision as of 08:56, 5 September 2011

Sumber: http://www.vogella.de/articles/Logging/article.html

Tulisan ini menjelaskan bagaimana cara menggunakan API di program Java. Termasuk cara membuat logger HTML.


1. Overview 1.1. Logging in Java

The JDK contains the "Java Logging API". Via a logger you can save text to a central place to report on errors, provide additional information about your program, etc. This logging API allows to configure how messages are written by which class with which priority. 1.2. Create a logger

The package java.util.logging provides the logging capabilities via the class Logger.

To create a logger in your Java coding.

import java.util.logging.Logger;

private final static Logger LOGGER = Logger.getLogger(MyClass.class .getName());


1.3. Level

The log levels define the severity of a message. The class Level is used to define which messages should be written to the log.

Die Log Levels in descending order are:

   SEVERE (highest)
   WARNING
   INFO
   CONFIG
   FINE
   FINER
   FINEST

In addition to that you have also the levels OFF and ALL to turn the logging of or to log everything.

For example the following will set the logger to level info which means all messages with severe, warning and info will be logged.

LOGGER.setLevel(Level.INFO);


1.4. Handler

Each logger can have access to several handler.

The handler receives the log message from the logger and exports it to a certain target

A handler can be turn off with setLevel(Level.OFF) and turned on with setLevel(...)

You have several standard handler, e.g.

ConsoleHandler: Write the log message to console

FileHandler: Writes the log message to file

Log Levels INFO and higher will be automatically written to the console.

1.5. Formatter

Each handlers output can be configured with a formatter

Available formatter

SimpleFormatter Generate all messages as text

XMLFormatter Generates XML output for the log messages

You can also build your own formatter. The following is an example of a formatter which will use create HTML output.

package logging;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;

//This custom formatter formats parts of a log record to a single line
class MyHtmlFormatter extends Formatter
{
	// This method is called for every log records
	public String format(LogRecord rec)
	{
		StringBuffer buf = new StringBuffer(1000);
		// Bold any levels >= WARNING

buf.append(""); buf.append("");

		if (rec.getLevel().intValue() >= Level.WARNING.intValue())
		{
			buf.append("");
			buf.append(rec.getLevel());
			buf.append("");
		} else
		{
			buf.append(rec.getLevel());
		}

buf.append(""); buf.append("");

		buf.append(calcDate(rec.getMillis()));
		buf.append(' ');
		buf.append(formatMessage(rec));
		buf.append('\n');

buf.append(""); buf.append("\n"); return buf.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 "<HTML>\n<HEAD>\n" + (new Date()) + "\n</HEAD>\n<BODY>\n

\n"
 				+ "<table border>\n  "
 				+ "<tr><th>Time</th><th>Log Message</th></tr>\n";
 	}
 
 	// This method is called just after the handler using this
 	// formatter is closed
 	public String getTail(Handler h)
 	{
 		return "</table>\n  

</BODY>\n</HTML>\n";

	}
} 


1.6. Log Manager

The log manager is responsible for creating and managing the logger and the maintenance of the configuration.

We could set the logging level for a package, or even a set of packages, by calling the LogManager.setLevel(String name, Level level) method. So, for example, we could set the logging level of all loggers "logging" to Level.FINE by making this call:

LogManager.getLogManager().setLevel("logging", Level.FINE)


1.7. Best Practices

It is common practice to use the fully qualified name of each class whose activity is being logged as a message category because this allows developers to fine-tune log settings for each class.

Using the fully qualified class name of your class as the name of your Logger is the approach recommended by the Logging API documentation.

2. Example

This example is stored in the project "de.vogella.logger".

Create your own formatter.

package logging;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;

//This custom formatter formats parts of a log record to a single line
class MyHtmlFormatter extends Formatter
{
	// This method is called for every log records
	public String format(LogRecord rec)
	{
		StringBuffer buf = new StringBuffer(1000);
		// Bold any levels >= WARNING

buf.append(""); buf.append("");

		if (rec.getLevel().intValue() >= Level.WARNING.intValue())
		{
			buf.append("");
			buf.append(rec.getLevel());
			buf.append("");
		} else
		{
			buf.append(rec.getLevel());
		}

buf.append(""); buf.append("");

		buf.append(calcDate(rec.getMillis()));
		buf.append(' ');
		buf.append(formatMessage(rec));
		buf.append('\n');

buf.append(""); buf.append("\n"); return buf.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 "<HTML>\n<HEAD>\n" + (new Date()) + "\n</HEAD>\n<BODY>\n

\n"
 				+ "<table border>\n  "
 				+ "<tr><th>Time</th><th>Log Message</th></tr>\n";
 	}
 
 	// This method is called just after the handler using this
 	// formatter is closed
 	public String getTail(Handler h)
 	{
 		return "</table>\n  

</BODY>\n</HTML>\n";

	}
} 


Initialize the logger.

package logging;

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class MyLogger { 
	static private FileHandler fileTxt;
	static private SimpleFormatter formatterTxt;

	static private FileHandler fileHTML;
	static private Formatter formatterHTML;

	static public void setup() throws IOException {
		// Create Logger
		Logger logger = Logger.getLogger("");
		logger.setLevel(Level.INFO);
		fileTxt = new FileHandler("Logging.txt");
		fileHTML = new FileHandler("Logging.html");

		// Create txt Formatter
		formatterTxt = new SimpleFormatter();
		fileTxt.setFormatter(formatterTxt);
		logger.addHandler(fileTxt);

		// Create HTML Formatter
		formatterHTML = new MyHtmlFormatter();
		fileHTML.setFormatter(formatterHTML);
		logger.addHandler(fileHTML);
	}
} 


Use the logger.

package logging;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class UseLogger {
	// Always use the classname, this way you can refactor
	private final static Logger LOGGER = Logger.getLogger(UseLogger.class
			.getName());

	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();
		try {
			MyLogger.setup();
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("Problems with creating the log files");
		}
		logger.writeLog();
	}
}



Referensi

Pranala Menarik