Home > Articles > Programming > Java

This chapter is from the book

Logging

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

%BEA_HOME%\user_domains\mydomain\myserver

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" 
    "http://www.bea.com/servers/wls600/msgcat.dtd">
<message_catalog
  i18n_package="com.sams.learnweblogic7.msg"
  l10n_package="weblogic.i18n"
  subsystem="MyAppModule"
  version="1.0"
  baseid="500000"
  endid="500100"
  loggables="false"
  >

  <!-- MyApp debug message one.-->
  <logmessage
   messageid="500000"
   datelastchanged="1026791920293"
   datehash="1460152857"
   severity="error"
   method="debug"
   stacktrace="true"
   >
   <messagebody>
     Error has occurred in method method1().
   </messagebody>
   <messagedetail>
     Error has occurred in method method1() of class MyApp.
   </messagedetail>
   <cause>
     Input data incorrect.
   </cause>
   <action>
     Verify input data.
   </action>
  </logmessage>
</message_catalog>

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 = { };
  MessageLogger.log(
    "500000",
    args,
    "weblogic.i18n.MyAppMsgLogLocalizer");
  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;
  MyApp()
  {
     // set the debug flag
     Properties inputProp = new Properties();
     debugFlag = Boolean.getBoolean(inputProp.getProperty("DEBUG_FLAG"));
  }
  
  public void myMethod1()
  {
     ...
     // perform exception handling
     if(debugFlag)
     {
       MyAppMsgLogger.debug();
     }
  }
}

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;
     System.out.println(myWLN.getMessage());
  }
}

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()
  {
     try
     {
       // 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020