WAS v8.5 > Troubleshoot > Add logging and tracing to the application > Use Java logging in an applicationUse 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.
- 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.DETAILFor trace use:
Level.FINE Level.FINER Level.FINEST
- 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.
- Avoid using the logrb method. This method leads to inefficient caching of resource bundles and poor performance.
- 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:// note - generally avoid use of FINE, FINER, FINEST levels for messages to be consistent with // WAS String componentName = "com.ibm.websphere.componentX"; String resourceBundleName = "com.ibm.websphere.componentX.Messages"; Logger logger = Logger.getLogger(componentName, resourceBundleName); // "Convenience" methods - not generally recommended due to lack of class / method names // - cannot specify message substitution parameters // - cannot specify class and method names if (logger.isLoggable(Level.SEVERE)) logger.severe("MSG_KEY_01"); if (logger.isLoggable(Level.WARNING)) logger.warning("MSG_KEY_01"); if (logger.isLoggable(Level.INFO)) logger.info("MSG_KEY_01"); if (logger.isLoggable(Level.CONFIG)) logger.config("MSG_KEY_01"); // log methods are not generally used due to lack of class and method names // - enable use of WAS-specific levels // - enable use of message substitution parameters // - cannot specify class and method names if (logger.isLoggable(WsLevel.FATAL)) logger.log(WsLevel.FATAL, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(Level.SEVERE)) logger.log(Level.SEVERE, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(Level.WARNING)) logger.log(Level.WARNING, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(WsLevel.AUDIT)) logger.log(WsLevel.AUDIT, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(Level.INFO)) logger.log(Level.INFO, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(Level.CONFIG)) logger.log(Level.CONFIG, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(WsLevel.DETAIL)) logger.log(WsLevel.DETAIL, "MSG_KEY_01", "parameter 1"); // logp methods are the way to log // - enable use of WAS-specific levels // - enable use of message substitution parameters // - enable use of class and method names if (logger.isLoggable(WsLevel.FATAL)) logger.logp(WsLevel.FATAL, className, methodName, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(Level.SEVERE)) logger.logp(Level.SEVERE, className, methodName, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(Level.WARNING)) logger.logp(Level.WARNING, className, methodName, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(WsLevel.AUDIT)) logger.logp(WsLevel.AUDIT, className, methodName, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(Level.INFO)) logger.logp(Level.INFO, className, methodName, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(Level.CONFIG)) logger.logp(Level.CONFIG, className, methodName, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(WsLevel.DETAIL)) logger.logp(WsLevel.DETAIL, className, methodName, "MSG_KEY_01", "parameter 1"); // logrb methods are not generally used due to diminished performance of switching resource bundles dynamically // - enable use of WAS-specific levels // - enable use of message substitution parameters // - enable use of class and method names String resourceBundleNameSpecial = "com.ibm.websphere.componentX.MessagesSpecial"; if (logger.isLoggable(WsLevel.FATAL)) logger.logrb(WsLevel.FATAL, className, methodName, resourceBundleNameSpecial, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(Level.SEVERE)) logger.logrb(Level.SEVERE, className, methodName, resourceBundleNameSpecial, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(Level.WARNING)) logger.logrb(Level.WARNING, className, methodName, resourceBundleNameSpecial, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(WsLevel.AUDIT)) logger.logrb(WsLevel.AUDIT, className, methodName, resourceBundleNameSpecial, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(Level.INFO)) logger.logrb(Level.INFO, className, methodName, resourceBundleNameSpecial, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(Level.CONFIG)) logger.logrb(Level.CONFIG, className, methodName, resourceBundleNameSpecial, "MSG_KEY_01", "parameter 1"); if (logger.isLoggable(WsLevel.DETAIL)) logger.logrb(WsLevel.DETAIL, className, methodName, resourceBundleNameSpecial, "MSG_KEY_01", "parameter 1");For trace, or content not localized, the following sample applies:// note - generally avoid use of FATAL, SEVERE, WARNING, AUDIT, // INFO, CONFIG, DETAIL levels for trace // to be consistent with WAS String componentName = "com.ibm.websphere.componentX"; Logger logger = Logger.getLogger(componentName); // Entering / Exiting methods are used for non trivial methods if (logger.isLoggable(Level.FINER)) logger.entering(className, methodName); if (logger.isLoggable(Level.FINER)) logger.entering(className, methodName, "method param1"); if (logger.isLoggable(Level.FINER)) logger.exiting(className, methodName); if (logger.isLoggable(Level.FINER)) logger.exiting(className, methodName, "method result"); // Throwing method is not generally used due to lack of message - use logp with a throwable parameter instead if (logger.isLoggable(Level.FINER)) logger.throwing(className, methodName, throwable); // Convenience methods are not generally used due to lack of class / method names // - cannot specify message substitution parameters // - cannot specify class and method names if (logger.isLoggable(Level.FINE)) logger.fine("This is my trace"); if (logger.isLoggable(Level.FINER)) logger.finer("This is my trace"); if (logger.isLoggable(Level.FINEST)) logger.finest("This is my trace"); // log methods are not generally used due to lack of class and method names // - enable use of WAS-specific levels // - enable use of message substitution parameters // - cannot specify class and method names if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "This is my trace", "parameter 1"); if (logger.isLoggable(Level.FINER)) logger.log(Level.FINER, "This is my trace", "parameter 1"); if (logger.isLoggable(Level.FINEST)) logger.log(Level.FINEST, "This is my trace", "parameter 1"); // logp methods are the recommended way to log // - enable use of WAS-specific levels // - enable use of message substitution parameters // - enable use of class and method names if (logger.isLoggable(Level.FINE)) logger.logp(Level.FINE, className, methodName, "This is my trace", "parameter 1"); if (logger.isLoggable(Level.FINER)) logger.logp(Level.FINER, className, methodName, "This is my trace", "parameter 1"); if (logger.isLoggable(Level.FINEST)) logger.logp(Level.FINEST, className, methodName, "This is my trace", "parameter 1"); // logrb methods are not applicable for trace logging because no localization is involvedThere 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.
The following example shows a 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 enables you 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
- Loggers
Loggers are used by applications and runtime components to capture message and trace events.- Log handlers
Log handlers write log record objects to output devices like log files, sockets, and notification mechanisms.- Log levels
Levels control which events are processed by Java logging. WAS controls the levels of all loggers in the system.- Log filters
Log filters help control more detailed logging settings that are not handled by usual log level settings.- Log formatters
Log formatters format log messages so they can be used by various log handlers.
Related
Configure the logger hierarchy
Create log resource bundles and message files