Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book


In order to store the output generated by the application that is displayed on the console, "stdout" can be written to a log file.

Output generated as a result of debugging or tracing statements can be easily redirected to a log file. The advantage of using log files to store the output is that you can view the output independently of the application being executed. For example, the output generated by debug statements can be viewed by a developer and analyzed much more easily than having to scan the statements scrolling by on the console! Similarly, it makes a lot more sense to have the output of trace statements logged to a log file. The log file can then be independently analyzed by developers to help them understand what actions took place when a problem occurred.

The following code snippet shows the use of a log file for logging trace and debug statements:

class MyLoggingHelper
  public static int WARNING = 0;
  public static int LOW = 1;
  public static int MEDIUM = 2;
  public static int HIGH = 3;

  private static SimpleDateFormat sdf =
sdf.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); private static FileWriter logFileWriter; public openLogFile(String inpFileName) { logFileWriter = new FileWriter(inpFileName); } public static void debug(int severityLevel, Object inpObj, String message) { logFileWriter.write("*******************************"); logFileWriter.write("DEBUG for " + inpObj); logFileWriter.write("Severity Level: " + severityLevel); logFileWriter.write("Message: " + message); logFileWriter.write("*******************************"); } public static void trace(Object inpObj, String message) { logFileWriter.write("*******************************"); logFileWriter.write ("TRACE for " + inpObj); logFileWriter.write ("Date and Timestamp: " + sdf.format(new Date())); logFileWriter.write ("Message: " + message); logFileWriter.write ("*******************************"); } public closeLogFile() { logFileWriter.close(); } }

Each of the domains in WebLogic Server has its own log file. The log file named myserver.log is located in the myserver directory of every domain that is present in the WebLogic Server. For example, for the domain mydomain, the log file myserver.log is located in the directory


Figure 17.1 shows the directory structure where the log files are located in WebLogic Server.

Figure 17.1 Directory structure showing the log file in the mydomain domain in WebLogic Server.

Log files can get really huge if proper housekeeping is not done. WebLogic Server keeps the size of the active log file relatively small and it archives the remaining logged data in archived log files.

Now you will see how WebLogic Server supports logging for applications and components deployed on WebLogic Server.

WebLogic's Support for Logging

WebLogic Server provides an entire logging framework for applications and components that are deployed on it. The logging framework spans logging debug and error messages to viewing the logged messages in the Administration Console. It also has an added ability to listen for logged messages.

WebLogic Server provides a log file to log messages, a Log Manager that maintains and manipulates the log messages, a filter to filter the types of logged messages, and a Log Broadcaster to send the filtered log messages to the central administration server (if the WebLogic Servers are arranged in a cluster). On the WebLogic Server that acts as an administration server, a listener is present to listen for the broadcasted log messages. These broadcasted messages are then filtered, and a subset of the broadcasted messages are then recorded so that they can be viewed later.

WebLogic Server uses the i18n internationalization framework that comes with the JDK. The i18n framework enables applications to define and use messages in different languages in Java applications. WebLogic Server leverages this ability to specify messages for different languages or message formats for its logging framework.

The logging services provided by WebLogic Server fall under three main areas: logging messages to the WebLogic Server log, viewing the WebLogic Server log, and broadcasting log messages to the administration server. You'll examine these services next.

Logging Messages to the WebLogic Server Log

Before you can log messages from your application, you'll need to create the logged messages. Log messages in WebLogic Server are bundled together in a message catalog XML file. Use the WebLogic Message Editor (weblogic.MsgEditor) utility to create these log messages. Log messages in the message catalog can contain parameters if required. A sample message catalog (MyAppMsg.xml) XML file is given here:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE message_catalog PUBLIC "weblogic-message-catalog-dtd" 

  <!-- MyApp debug message one.-->
     Error has occurred in method method1().
     Error has occurred in method method1() of class MyApp.
     Input data incorrect.
     Verify input data.

After creating the log messages, you need to compile the message catalog using the i18ngen utility. The i18ngen (weblogic.18ngen) utility parses the message catalog and generates a Java class for the message catalog. The different messages in the catalog are converted into methods of the generated Java class. To generate the Java class for the message catalog MyAppMsg.xml (created in the preceding code), give this command:

java weblogic.18ngen –i18n MyAppMsg.xml

This will create the Java file MyAppMsgLogger.java. The code of this generated class is as follows:

package com.sams.learnweblogic7.msg;

import weblogic.logging.MessageLogger;
import weblogic.logging.Loggable;
import java.util.MissingResourceException;
 * Copyright (c) 2002 by BEA Systems, Inc. All Rights Reserved.
 * @exclude
public class MyAppMsgLogger
  * Error has occurred in method method1().
  * @exclude
  * messageid: 500000
  * severity:  error
 public static String debug() {
  Object [] args = { };
  return "500000";

Finally, applications or application components can use this Java class to log the messages at different points as required:

import com.sams.learnweblogic7.msg.*;

class MyApp
  public boolean debugFlag = false;
     // set the debug flag
     Properties inputProp = new Properties();
     debugFlag = Boolean.getBoolean(inputProp.getProperty("DEBUG_FLAG"));
  public void myMethod1()
     // perform exception handling

Viewing the WebLogic Server Log

The messages generated by different applications and components in WebLogic Server are logged to a log file. The contents of the log file can be viewed using the Administration Console. Because you can have different domains in an instance of a WebLogic Server, there are domain-specific message logs that can be viewed using the Administration Console. In addition to viewing log messages, you can also search and configure log file settings using the Administration Console.

Figure 17.2 shows the contents of the log file viewed using the Administration Console.

Figure 17.2 Administration Console displaying the contents of a log file of the myserver server in the mydomain domain in WebLogic Server.

Notification Mechanism for the WebLogic Server Log

WebLogic Server provides a notification mechanism based on the Java Management Extensions (JMX) API to enable broadcasting of log messages to the administration server. Any application or component deployed on any WebLogic Server instance can write its messages to the log file. The administration server listens for these log messages and copies them over to the domain-wide log file. The caveat is that the log messages with the severity level DEBUG are not broadcast to the administration server.

In addition, you can write custom listeners for the log messages. You can also write monitoring applications that listen for log messages, similar to the administration server. Then your monitoring application can perform appropriate action after interpreting the log messages, such as sending an e-mail (using the JavaMail API) or pager notification to the administrator of the application or component that failed.

To create a notification listener used by a monitoring application that is located in the same JVM as the application that is being monitored, your monitoring application needs to implement the handleNotification() method of the javax.management.Notification.NotificationListener interface. The handleNotification() method receives a WebLogicNotification object (a subclass of the Notification base class) as a parameter whenever the monitoring application receives a log message. The contents of the WebLogicNotification object are the log message and other relevant data:

import javax.management.Notification.*;

class MyMonitoringApp implements NotificationListener
  WebLogicNotification myWLN = null;
  public void handleNotificationListener(
      Notification inpNotification, Object inpObj)
     myWLN = (WebLogicNotification) inpNotification;

For monitoring applications located on a physically different machine, the monitoring application must implement the RemoteNotificationListener interface instead.

As an alternative to this elaborate process of creating log messages in a catalog, you can use the weblogic.logging.NonCatalogLogger APIs provided by WebLogic Server. With the NonCatalogLogger APIs, you can embed debug messages directly in the source code of the application without any compiling of log messages. In addition, you can define severity levels such as DEBUG, INFO, WARNING, and ERROR for the log messages of your application.

A code snippet using the NonCatalogLogger API is given here:

import weblogic.logging.*;

class MyApp
  NonCatalogLogger myAppLogger = new NonCatalogLogger("MyApp.log");
  public void myMethod1()
       // do some processing
       // trace statement
       myAppLogger.info("Check point 1 – data reading succesful!");
       // warning statement
       if(inpData.length() > MAX_LENGTH_POSSIBLE)
          myAppLogger.warning("Input data is longer than required.
Please check the input data!"); } catch(Exception e) { // exception logging myAppLogger.debug("Error occurred while reading data!" +
e.printStackTrace()); } } }

Finally, take a look at the support provided in the new JDK 1.4 for logging in Java applications.

Logging Support in JDK 1.4

Sun has provided explicit support for logging in Java applications using a new API in the JDK 1.4 called the Logger API. The Logger API consists of the following set of classes and interfaces:

  • Logger—A Logger class is the most important class used in the Logger API. An instance of the Logger class is used by an application to log the messages and interact with the logging framework. The Logger class provides different overloaded log() methods that can be used by applications to write messages.

  • Handler—A Handler class obtains the logged messages in the form of LogRecords from the logger and forwards them to the appropriate media for writing. The different handlers that are available are ConsoleHandler, FileHandler, SocketHandler, StreamHandler, and MemoryHandler. These handlers are specialized for writing the logged messages to the console, developer-specified file, network connection, binary stream, or buffer in memory.

  • LogRecord—The LogRecord class encapsulates a single logged message. A log record contains the logged message, message level, information about the class that logs the information, and the time stamp.

  • Filter—In addition to the log levels, if control over any logged record is required, the Filter interface should be implemented.

  • Formatter—The logging API also provides the ability to format the logged messages. This is done using the two formatter classes provided: SimpleFormatter and XMLFormatter. The SimpleFormatter class formats the logged messages as text data while the XMLFormatter class formats the messages in an XML file.

  • Log level—A developer can define levels for the logged messages. The different levels available are: SEVERE, WARNING, INFO, CONFIG, FINE, FINER, and FINEST. These levels are used to control and interpret the logging output. To switch the logging feature off or on, there are two additional levels provided: OFF and ALL.

  • + Share This
  • 🔖 Save To Your Account