Installing ALUI Portal

Document Sample
Installing ALUI Portal Powered By Docstoc
					              Chapter 3 – Logging and Configuration, Part I
                                               Logging
Logging enables you to capture important events inside your program and can aid you during the
debugging process. It offers finer granularity and better control over the System.out.println()
method. If you are only interested with IDK logging, you can skip ahead to section 2 of this
chapter.

Depending on which platform (.NET or Java), you can find a wealth of logging utilities. One of
the leading tools is the Apache Log4J framework. (http://logging.apache.org/ ) It is based on the
Apache License, allowing you to use the Log4J library inside your software, including
proprietary applications. There are also related projects for .NET, PHP, C#, C++, etc.1

1 Log4J
1.1 Setup
To use the Log4J library, you must include the appropriate jar file. The latest version (at the time
of writing this guide) is log4-1.2.14.jar. It is about 359 KB in size. I just add it as a library in the
IDE, allowing me to reuse it on several projects without additional setup effort. (You may also
add the API docs in the setup process by pointing to the appropriate folder or the API jar file.)




   1
     Log 4 .Net project - http://logging.apache.org/log4net/ &
    http://www.devhood.com/tools/tool_details.aspx?tool_id=712
   Log4cxx - http://logging.apache.org/log4cxx/
   Chainsaw v2 – a graphic log viewer. http://logging.apache.org/log4j/docs/chainsaw.html
             a. Download from ( http://logging.apache.org/log4j/docs/webstart/chainsaw/chainsaw-bundle.zip )

                                                                                                               1
1.2 Concept
The Log4J library introduces several important concepts:
1. Logging granularity – Allowing you greater control over the log output than
   System.out.println(). (Debug < Info < Warn < Error < Fatal)
          a. Debug – Detailed application and parameter tracing.
          b. Info – Normal application event recording
          c. Warn – Minor problem
          d. Error – Significant problem, but is not a showstopper.
          e. Fatal - Major problem, could potential crash your application.

2. Appenders & Layout – Where to send your log output, appenders include,
         a. FileAppender – Subclass: RollingFileAppender, DailyRollingFileAppender
         b. ConsoleAppender
         c. JDBCAppender
         d. JMSAppender
         e. NTEventLogAppender
         f. SMTPAppender
         g. SocketAppender
         h. Nullappender,
         i. Etc.

           Layout lets you specify the format of your log out. e.g. Text output
       log4j.appender.R.layout=org.apache.log4j.PatternLayout
       %d{dd MMM yyyy HH:mm:ss} -- %p -- %c -- %m%n
             ----------
             Results in
             ----------
       27 Sep 2006 18:00:22 -- INFO -- com.uhg.ovations.pbmui.InitServlet --
       InitServlet has been started.

           XML output can be used with Chainsaw utility.
       log4j.appender.R.layout=org.apache.log4j.xml.XMLLayout      ----------
             Results in
             ----------
       <log4j:event logger="logging.LogMe" timestamp="1160422555484"
       level="INFO" thread="main">
       <log4j:message><![CDATA[LogMe has been started.]]></log4j:message>
       </log4j:event>

       <log4j:event logger="logging.LogMe" timestamp="1160422555484"
       level="DEBUG" thread="main">
       <log4j:message><![CDATA[calling debug method.]]></log4j:message>

3. Logger hierarchy – Loggers are stored in a hierarchical structure, e.g. com.foo.bar.Myclass.
   When you set the logging level (Info) on a package (com.foo.bar), it automatically flow
   downward to its child, (com.foo.bar.Class1 and com.foo.bar.Class2), unless you explicitly
   override it. There is always a root logger available, Logger.getRootLogger().

1.3 How to use Log4J
Import the Log4J library.
       //For Java class:
       import org.apache.log4j.Logger;
                                                                                                  2
       //For JSP:
       <%@page import="org.apache.log4j.*"%>

You can get a logger object by calling the Logger.getLogger() method.
       // Log4J does not make assumption to have a default appender. Later we
       will use a different Log4j Configurator.
       BasicConfigurator.configure();
       Logger ul = Logger.getLogger(“a descriptive string”);
       Logger ul = Logger.getLogger(Myclass.class);

You may start logging by invoking one the logging methods, e.g. info(), fatal(), warn(), … You
may set logging level as well. Level object has predefined constants, e.g. info, fatal, warn, etc.
       //Set logging level, e.g. Level.All, Level.ERROR, Level.INFO.
       ul.setLevel(Level.INFO);
       //Start logging
       ul.info(“This is my logging output.”);
       ul.warn(“This is a warning.”);
       ul.debug(“This debug message will not appear”);

By using BasicConfigurator, the logger writes output to the console. However, you can specify a
different appender, e.g. FileAppender. The following code shows you how to use the
PropertyConfigurator class.
      // You may use PropertyConfigurator to load a Log4J configuration file.
      // This tells the Log4J to watch the property file and reload when the
file has been modified.
            PropertyConfigurator.configureAndWatch(propertyfile);
            System.out.println("Loading the log4j property file: -> " +
propertyfile);
      // After setting the Log4J configuraiton, you may use the logger.
            Logger ul = Logger.getLogger(Myclass.class);
            ul.inf(“logging to the output file specified by the
configuration.

The Log4J configuration can use an external properties file. An example is shown below.
#
# Log for Java configuration don't change unless you know what you doing
# The possible values here are debug, info, warn, error, fatal
#
log4j.rootCategory=info, R

#
# Using Rolling File Appender
#
log4j.appender.R=org.apache.log4j.RollingFileAppender

#
# This is the file that becomes the log file. Older log files are renamed as
fileName.log.1 fileName.log.2 etc.
#
log4j.appender.R.File=C:\\My
Documents\\g6_book\\java_src\\logging\\logs\\out.log

#
# The maximum size of the log file, good idea to keep the size small.
#

                                                                                                 3
log4j.appender.R.MaxFileSize=100KB

#
# This defines the no of log files to keep. Since this is a rolling file
system, after the number of
# files reaches this number, the oldest file is rewritten
#
log4j.appender.R.MaxBackupIndex=20

#
# Dont change this
#
log4j.appender.R.layout=org.apache.log4j.PatternLayou
#Alternatively, you may use xml, without the conversation pattern.
# log4j.appender.R.layout=org.apache.log4j.xml.XMLLayout

#
# This defines the way comments are written to the log file, for e.g. %d
tells the logger to write the date
# for a full list see the log4j manual. %p is the priority (debug, info etc
as defined above)
# %c is the name of the registered logger, e.g. Class.class or index.jsp etc.
#
log4j.appender.R.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss} -- %p --
%c -- %m%n
                                        Log4J.properties

The log output is saved to out.log file, shown below.
27 Sep 2006 17:57:48 -- INFO -- com.uhg.ovations.pbmui.InitServlet --
InitServlet has been started.
27 Sep 2006 17:57:48 -- INFO -- com.uhg.ovations.pbmui.Konfig -- Creating a
new instance of the global configuraiton properties.
27 Sep 2006 17:57:48 -- INFO -- com.uhg.ovations.pbmui.Konfig -- Reloading
the global configuration file: C:\\Documents and
Settings\\rgao.NA\\Desktop\\ajax_toolkit\\UHGCommon\\web\\WEB-
INF\\globalconfig.properties
27 Sep 2006 17:57:48 -- INFO -- com.uhg.ovations.pbmui.Konfig -- ---The list
of global properties----
                                         Log output file

1.4 Chainsaw
Chainsaw is a GUI tool for displaying log output. It can color-code different logging outputs. To
use it, you must use XMLLayout pattern for your appender.
log4j.appender.R.layout=org.apache.log4j.xml.XMLLayout

which produces following log file. To start chainsaw, use chainsaw.bat command.
<log4j:event logger="logging.LogMe" timestamp="1160422555484" level="INFO"
thread="main">
<log4j:message><![CDATA[LogMe has been started.]]></log4j:message>
</log4j:event>

<log4j:event logger="logging.LogMe" timestamp="1160422555484" level="DEBUG"
thread="main">
<log4j:message><![CDATA[calling debug method.]]></log4j:message>
</log4j:event>



                                                                                                4
1.5 Automatic Log4J Initialization
If you are developing a web application, it is a good idea to configure and initialize the Log4J
library in either a startup servlet (Java) or an initialization class (.NET). You can pass in the
configuration file name through either web.xml (Java) or web.config (.NET). I provide you an
example for the Java application below.

/*
 * InitServlet.java
 *
 */

package logging;

import   java.io.File;
import   javax.servlet.*;
import   javax.servlet.http.*;
import   org.apache.log4j.Logger;
import   org.apache.log4j.PropertyConfigurator;

/**
 *
 * @author rgao
*/
public class InitServlet extends HttpServlet {
                                                                                                    5
    private static boolean initialized = false;

    public void init(ServletConfig config) throws ServletException{
        super.init(config);
        if (initialized == false ) {
            System.out.println("****Initializing Log4J.");
            //Set up log4J
            String props = config.getInitParameter("log4j_property_file");
            props = config.getServletContext().getRealPath(props);
            System.out.println("Using Log4J property file: " + props);
            if(props == null || props.length() == 0 || !(new
File(props)).isFile()) {
                System.err.println(
                         "ERROR: Invalid Lo4J property file. " +
                         "Please check the web.xml");
                throw new ServletException("Invalid log4j property file.");
            }

            InitLogger.initialize(props);

            Logger logger = Logger.getLogger(InitServlet.class );
            logger.info("InitServlet has been started.");

            //read in global configuration file – we will cover this in the
next section.
            initialized = true;
        }
    }
}
                                InitServlet.java

/*
 * InitLogger.java
 *
 * Created on September 27, 2006, 3:08 PM
 */

package logging;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Logger;

/**
 *
 * @author rgao
 */
public class InitLogger {

    private static boolean initialized = false;

    private InitLogger() {
        //
    }
    public static boolean isInitialized() {
        return initialized;
    }

    public static void initialize(String propertyfile) {
        if (!isInitialized()) {
            PropertyConfigurator.configureAndWatch(propertyfile);

                                                                              6
            System.out.println("Loading the log4j property file: -> " +
propertyfile);
        }
        initialized = true;
    }
}
                                       InitLogger.java

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <servlet>
        <description>InitServlet</description>
        <servlet-name>InitServlet</servlet-name>
        <servlet-class>logging.InitServlet</servlet-class>
        <init-param>
            <description>Log4J property file</description>
            <param-name>log4j_property_file</param-name>
            <param-value>\\WEB-INF\\xml.properties</param-value>
        </init-param>
        <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>InitServlet</servlet-name>
        <url-pattern>/initServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
      <welcome-file>
            index.jsp
        </welcome-file>
    </welcome-file-list>
</web-app>
                                          Web.xml

2 Plumtree Logging Framework
The Plumtree logging framework is built on the top of the Log4J framework and the
OpenFoundation library (which provides cross-platform, Java and .Net support) and provides
you some additional tools.
   1. IDK(EDK) – based on the Log4J framework
          a. com.plumtree.remote.logging package for Java development and works in
              conjunction with web.xml (Java servlet containers).
          b. Plumtree.Remote.Logging Namespace for .Net development and works in
              conjunction with Web.config (Microsoft IIS).
   2. Log viewers
          a. PTSPY – A GUI tool for displaying the portal log.
          b. ALI Logger – A background logging tool. The default location for all the logs are
              stored in <portal_home>/ptlogging/logs directory.
          c. Console Logger – Displays the log output in a console window.
                                                                                             7
2.1 How to use the Portal Logging Framework
The IDK remote logging library has two interfaces.
      1. ILogger – equivalent to a Logger object in the Log4J framework. It implements the 5
          main logging levels (Debug, Info, Warn, Error, and Fatal). Additionally, it provides
          supplemental functions for Action (trace for significant event), Function (marker for
          beginning and ending of a function), and Performance (program execution statics).
      2. LogFactory – equivalent to the LoggerFactory class in the Log4J framework.

2.2 How to use the Portal Logging Framework
It is simple to use the Portal logging Framework. You just need to declare it as environment
variables in the web-application’s configuration file (web.xml or web.config) which
automatically takes care of the logger configuration for you. The logger will be automatically
registered with the portal logging subsystem.

2.2.1 Java Portal Logging
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <env-entry>
        <env-entry-name>ptedk.VerboseLogging</env-entry-name>
        <env-entry-value>false</env-entry-value>
        <env-entry-type>java.lang.Boolean</env-entry-type>
    </env-entry>
    <env-entry>
        <env-entry-name>ptedk.LoggingApplicationName</env-entry-name>
        <env-entry-value>Logging Example</env-entry-value>
        <env-entry-type>java.lang.String</env-entry-type>
    </env-entry>
    <env-entry>
        <env-entry-name>ptedk.LogToNetwork</env-entry-name>
        <env-entry-value>true</env-entry-value>
        <env-entry-type>java.lang.Boolean</env-entry-type>
    </env-entry>
      (other stuff related to your servlet set up, etc.)
</web-app>
                                            Web.xml

To use the logger in the servlet, follow the following example.
String methodName = "init()";
ILogger logger = LogFactory.getLogger(NewServlet.class.getName(),
methodName);

logger.functionBegin(methodName);

// get a timestamp to measure performance of this function
long performanceStartTicks = logger.performanceBegin();

logger.action("Action log messages are on by default in the log receiver.");

// demonstrates the available logging levels and shows use of token
// substitution in format strings to construct messages.
String levelDescriptionFormat = "{0} level messages are {1} by default in the
IDK log receiver.";
                                                                                                 8
// debug() through fatal() are increasingly serious warning messages.
// By comparison, the message types action, function, and performance
// are generally "info" or "debug" level, with Action perhaps representing
// a message more important than "Info". Function and performance messages
// are off by default.
logger.debug(levelDescriptionFormat, "Debug", "off"); //Turned off by default
logger.info(levelDescriptionFormat, "Info", "off"); //Turned off by default
logger.warn(levelDescriptionFormat, "Warn", "on");
logger.error(levelDescriptionFormat, "Error", "on");
logger.fatal(levelDescriptionFormat, "Fatal", "on");

// send log message with time since performanceBegin
logger.performanceEnd(methodName, performanceStartTicks);

// send log message that function is ending
logger.functionEnd(methodName);
                                     PtLogger code snippet

Then, you can view your log output with PTSpy.




2.2.2 .NET Logging
To use portal logging with .Net platform, you just add following lines to the web.config file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
      <add key="ptedk.LoggingApplicationName" value="Logging-Example-DotNet"
/>
      <add key="ptedk.LogToNetwork" value="true" />
      <add key="ptedk.VerboseLogging" value="true" />
   </appSettings>
   <system.web>
      (Other stuff)
   <system.web>
</configuration>
                                           Web.config

using   System;
using   System.Collections;
using   System.ComponentModel;
using   System.Data;
using   System.Drawing;
using   System.Web;
using   System.Web.SessionState;
                                                                                                 9
using   System.Web.UI;
using   System.Web.UI.WebControls;
using   System.Web.UI.HtmlControls;
using   Plumtree.Remote.Logging;

namespace logging
{
       /// <summary>
       /// Summary description for WebForm1.
       /// </summary>
       public class EDK_Logging_DotNet : System.Web.UI.Page
       {
             private void Page_Load(object sender, System.EventArgs e)
             {
                   if (!(LogFactory.IsInitialized()))
                   {
                         Response.Write("EDK logger is not initialized.<br>");
                         LogFactory.Initialize("Logging_with_edk_dotNet",
true);
                   }
                   Response.Write("EDK logger has been initialized.<br>");
                   // Put user code to initialize the page here
                   // send log message that function is starting
                   String methodName = "init()";
                   ILogger logger = LogFactory.GetLogger(this.ToString(),
methodName);

                    logger.FunctionBegin(methodName);

                    // get a timestamp to measure performance of this function
                    long performanceStartTicks = logger.PerformanceBegin();

                    logger.Action("Action log messages are on by default in the
log receiver.");

                    // demonstrates the available logging levels and shows use
of token
                  // substitution in format strings to construct messages.
                  String levelDescriptionFormat = "{0} level messages are {1}
by default in the IDK log receiver.";
                  // debug() through fatal() are increasingly serious warning
messages.
                  //   By comparison, the message types action, function, and
performance
                  //   are generally "info" or "debug" level, with Action
perhaps representing
                  //   a message more important than "Info". Function and
performance messages
                  //   are off by default.
                  logger.Debug(levelDescriptionFormat, "Debug", "off");
                  logger.Info(levelDescriptionFormat, "Info", "off");
                  logger.Warn(levelDescriptionFormat, "Warn", "on");
                  logger.Error(levelDescriptionFormat, "Error", "on");
                  logger.Fatal(levelDescriptionFormat, "Fatal", "on");

                    // send log message with time since performanceBegin
                    logger.PerformanceEnd(methodName, performanceStartTicks);

                    // send log message that function is ending
                    logger.FunctionEnd(methodName);

                                                                                 10
              }
              #region Web Form Designer generated code
              override protected void OnInit(EventArgs e)
              {
                    //
                    // CODEGEN: This call is required by the ASP.NET Web Form
Designer.
                      //
                      InitializeComponent();
                      base.OnInit(e);
              }

              /// <summary>
              /// Required method for Designer support - do not modify
              /// the contents of this method with the code editor.
              /// </summary>
              private void InitializeComponent()
              {
                    this.Load += new System.EventHandler(this.Page_Load);
              }
              #endregion
       }
}
                                     C# code behind file.


2.2.3 Portal Logger Configuration Files
The portal provides three default configuration files inside the
<PT_HOME>/settings/ptlogging directory.
   1. consolelogger.xml – To be used with the console logger, which can be started by the
       <PT_HOME>\ptlogging\6.0\bin\consoleLogger.bat
   2. ptLogger.xml- The background ALUI logger, which ouputs the log to the
       <PT_HOME>/ptlogging/logs directory. By changing the appenders, you can easily
       write the output to a different location. See example below.
        <appender class="org.apache.log4j.DailyRollingFileAppender"
    name="WSServerLogFile">
            <layout class="com.plumtree.openlog.log4jbridge.MyPatternLayout"/>
            <param name="File" value="/c:/log/mylog.txt"/>
            <param name="Append" value="false"/>
            <param name="DatePattern" value="'.'yyyy-ww"/>
        </appender>
    3. ptSpy.xml – To be used the PtSpy for visual display.




                                                                                            11

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:10
posted:9/9/2011
language:English
pages:11