+

Search Tips   |   Advanced Search

Example: Creating custom formatters with java.util.logging


A formatter formats events. Handlers are associated with one or more formatters.

The mechanism for creating a customer formatter is the Formatter class support that is provided by the IBM Developer Kit, Java Technology Edition. If not familiar with formatters, as implemented by the Developer Kit, we can get more information from various texts, or by reading the API documentation for the java.util.logging API.

The following example shows a custom formatter:

import java.util.Date;
 import java.util.logging.Formatter;
 import java.util.logging.LogRecord;

/**
 * MyCustomFormatter formats the LogRecord as follows:
 * date   level   localized message with parameters 
 */ public class MyCustomFormatter extends Formatter {

  public MyCustomFormatter() {
    super();
  }

  public String format(LogRecord record) {
    
    
// Create a StringBuffer to contain the formatted record
    
// start with the date.
    StringBuffer sb = new StringBuffer();
    
    
// Get the date from the LogRecord and add it to the buffer
    Date date = new Date(record.getMillis());
    sb.append(date.toString());
    sb.append(" ");
    
    
// Get the level name and add it to the buffer
    sb.append(record.getLevel().getName());
    sb.append(" ");
     
    
// Get the formatted message (includes localization 
    
// and substitution of paramters) and add it to the buffer
    sb.append(formatMessage(record));
    sb.append("\n");

    return sb.toString();
  }
}




 

Related tasks


Set the logger hierarchy
Create log resource bundles and message files
Use a logger

 

Related


Example: Creating custom log handlers with java.util.logging
Example: Creating custom filters with java.util.logging
Example: Adding custom handlers, filters, and formatters