Troubleshoot > Add logging and tracing to the application > Use Java logging in an application

Use a logger

We can use Java logging to log messages and add tracing.

Java provides a log and trace package, java.util.logging, used to instrument the applications. This topic provides recommendations about how to use the log and trace package.

  1. Use WsLevel.DETAIL level and above for messages, and lower levels for trace. The WebSphere Application Server Extension API (the com.ibm.websphere.logging package) contains the WsLevel class.

    For messages use:

      WsLevel.FATAL
      Level.SEVERE
      Level.WARNING
      WsLevel.AUDIT
      Level.INFO
      Level.CONFIG
      WsLevel.DETAIL

    For trace use:

      Level.FINE
      Level.FINER
      Level.FINEST

  2. Use the logp method instead of the log or the logrb method. The logp method accepts parameters for class name and method name. The log and logrb methods will generally try to infer this information, but the performance penalty is prohibitive. In general, the logp method has less performance impact than the log or the logrb method.

  3. Avoid using the logrb method. This method leads to inefficient caching of resource bundles and poor performance.

  4. Use the isLoggable method to avoid creating data for a logging call that does not get logged. For example:

      if (logger.isLoggable(Level.FINEST)) {
        String s = dumpComponentState(); // some expensive to compute method   logger.logp(Level.FINEST, className, methodName, "componentX state 
      dump:\n{0}", s);
       }


Localized messages

The following sample applies to localized messages:

For trace, or content not localized, the following sample applies:

There may be occasions when we want to propagate log records to our own log handlers rather than participate in integrated logging. To use a stand-alone log handler, set the useParentHandlers flag to false in the application.The mechanism for creating a customer handler is the Handler class support provided by the IBM Developer Kit, Java Technology Edition. If we are not familiar with handlers, 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 sample shows a custom handler:

import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

/**
 * MyCustomHandler outputs contents to a specified file  */
public class MyCustomHandler extends Handler {

 FileOutputStream fileOutputStream;
 PrintWriter printWriter;

 public MyCustomHandler(String filename) {
  super();

  // check input parameter   if (filename == null || filename == "")
   filename = "mylogfile.txt";
  
  try {
   // initialize the file 
   fileOutputStream = new FileOutputStream(filename);
   printWriter = new PrintWriter(fileOutputStream);
    setFormatter(new SimpleFormatter());
  }
  catch (Exception e) {
   // implement exception handling...
  }
 }

 /* (non-API documentation)
  * @see java.util.logging.Handler#publish(java.util.logging.LogRecord)
  */
 public void publish(LogRecord record) {
  // ensure that this log record should be logged by this Handler
  if (!isLoggable(record))
   return;
  
  // Output the formatted data to the file   printWriter.println(getFormatter().format(record));
 }

 /* (non-API documentation)
  * @see java.util.logging.Handler#flush()
  */
 public void flush() {
  printWriter.flush();
 }

 /* (non-API documentation)
  * @see java.util.logging.Handler#close()
  */
 public void close() throws SecurityException {
  printWriter.close();
 }}

A custom filter provides optional, secondary control over what is logged, beyond the control provided by the level. The mechanism for creating a custom filter is the Filter interface support provided by the IBM Developer Kit, Java Technology Edition. If we are not familiar with filters, as implemented by the Developer Kit, we can get more information from various texts, or by reading the API documentation the for the java.util.logging API.

Custom filter:

/**
 * This class filters out all log messages starting with SECJ022E, SECJ0373E, or SECJ0350E.
 */
import java.util.logging.Filter;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.LogRecord;

public class MyFilter implements Filter {
 public boolean isLoggable(LogRecord lr) {
  String msg = lr.getMessage();
  if (msg.startsWith("SECJ0222E") || msg.startsWith("SECJ0373E") || msg.startsWith("SECJ0350E")) {
   return false;
  }
  return true;
 }}

//This code will register the above log filter with the root Logger's handlers (including the WAS system logs):
...
Logger rootLogger = Logger.getLogger("");
rootLogger.setFilter(new MyFilter());

A formatter formats events. Handlers are associated with one or more formatters. The mechanism for creating a custom formatter is the Formatter class support provided by the IBM Developer Kit, Java Technology Edition. If we are 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();
 }}

Adding custom handlers, filters, and formatters allows us to customize the logging environment beyond what can be achieved by the configuration of the default WAS logging infrastructure. The following example demonstrates how to add a new handler to process requests to the com.myCompany subtree of loggers (see Configure the logger hierarchy). The main method in this sample gives an example of how to use the newly configured logger.

import java.util.Vector;
import java.util.logging.Filter;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MyCustomLogging {

 public MyCustomLogging() {
  super();
 }

 public static void initializeLogging() {
  
  // Get the logger to attach a custom Handler to   String defaultResourceBundleName = "com.myCompany.Messages";
  Logger logger = Logger.getLogger("com.myCompany", defaultResourceBundleName);
  
  // Set up a custom Handler (see MyCustomHandler example)
  Handler handler = new MyCustomHandler("MyOutputFile.log");
  
  // Set up a custom Filter (see MyCustomFilter example)
  Vector acceptableLevels = new Vector();
  acceptableLevels.add(Level.INFO);
  acceptableLevels.add(Level.SEVERE);
  Filter filter = new MyCustomFilter(acceptableLevels);
  
  // Set up a custom Formatter (see MyCustomFormatter example)
  Formatter formatter = new MyCustomFormatter();

  // Connect the filter and formatter to the handler   handler.setFilter(filter);
  handler.setFormatter(formatter);
  
  // Connect the handler to the logger   logger.addHandler(handler);
  
  // avoid sending events logged to com.myCompany showing up in WebSphere   // Application Server logs   logger.setUseParentHandlers(false);
    
 }

 public static void main(String[] args) {
  initializeLogging();
  
  Logger logger = Logger.getLogger("com.myCompany");
  
  logger.info("This is a test INFO message");
  logger.warning("This is a test WARNING message");
  logger.logp(Level.SEVERE, "MyCustomLogging", "main", "This is a test SEVERE message");
 }}

When the above program is run, the output of the program is written to the MyOutputFile.log file. The content of the log is in the expected log file, as controlled by the custom handler, and is formatted as defined by the custom formatter. The warning message is filtered out, as specified by the configuration of the custom filter. The output is as follows:

C:\>type MyOutputFile.log
Sat Sep 04 11:21:19 EDT 2004 INFO This is a test INFO message Sat Sep 04 11:21:19 EDT 2004 SEVERE This is a test SEVERE message


Subtopics


Related


Configure the logger hierarchy
Create log resource bundles and message files


+

Search Tips   |   Advanced Search