Modified: logging/site/trunk/docs/log4cxx/manual.html URL: http://svn.apache.org/viewvc/logging/site/trunk/docs/log4cxx/manual.html?view=diff&rev=564410&r1=564409&r2=564410 ============================================================================== --- logging/site/trunk/docs/log4cxx/manual.html (original) +++ logging/site/trunk/docs/log4cxx/manual.html Thu Aug 9 15:34:47 2007 @@ -12,15 +12,13 @@ log4cxx - - Short introduction to log4j + Short introduction to log4cxx - @@ -43,7 +41,7 @@
- Last Published: 07/24/2007 + Last Published: 08/09/2007 | Apache > @@ -174,45 +172,28 @@ -

Short introduction to log4j: Ceki Gülcü, March 2002

-

- Copyright © 2000-2002 The Apache Software Foundation. All - rights reserved. This software is published under the terms of - the Apache Software License version 2.0, a copy of which has - been included in the LICENSE file shipped with the log4j - distribution. This document is based on the article "Log4j - delivers control over logging" published in November 2000 - edition of JavaWorld. However, the present article contains more - detailed and up to date information. The present short manual - also borrows some text from "The - complete log4j manual" by the same author (yours - truly).

+

Short introduction to log4cxx

Abstract

-

This document describes the log4j API, its unique features and -design rationale. Log4j is an open source project based on the work of +

This document describes the log4cxx API, its unique features and +design rationale. Log4cxx is an open source project based on the work of many authors. It allows the developer to control which log statements are output with arbitrary granularity. It is fully configurable at -runtime using external configuration files. Best of all, log4j has a +runtime using external configuration files. Best of all, log4cxx has a gentle learning curve. Beware: judging from user feedback, it is also quite addictive.

Introduction

-

Almost every large application includes its own logging or tracing -API. In conformance with this rule, the E.U. SEMPER project decided to write its -own tracing API. This was in early 1996. After countless enhancements, -several incarnations and much work that API has evolved to become -log4j, a popular logging package for Java. The package is distributed -under the Apache Software License, a -fully-fledged open source license certified by the open source initiative. The -latest log4j version, including full-source code, class files and -documentation can be found at http://logging.apache.org/log4j/. -By the way, log4j has been ported to the C, C++, C#, Perl, Python, -Ruby, and Eiffel languages.

+The log4cxx framework is patterned after log4j. +log4cxx is licensed under the +Apache License, +an open source license certified by the +Open Source Initiative. -

Inserting log statements into code is a low-tech method for +

Almost every large application includes its own logging or tracing +API. Inserting log statements into code is a low-tech method for debugging it. It may also be the only way because debuggers are not always available or applicable. This is usually the case for multithreaded applications and distributed applications at large.

@@ -226,31 +207,15 @@ development cycle, a sufficiently rich logging package can also be viewed as an auditing tool.

-

As Brian W. Kernighan and Rob Pike put it in their truly excellent -book "The Practice of Programming" -

-  As personal choice, we tend not to use debuggers beyond getting a
-  stack trace or the value of a variable or two. One reason is that it
-  is easy to get lost in details of complicated data structures and
-  control flow; we find stepping through a program less productive
-  than thinking harder and adding output statements and self-checking
-  code at critical places. Clicking over statements takes longer than
-  scanning the output of judiciously-placed displays. It takes less
-  time to decide where to put print statements than to single-step to
-  the critical section of code, even assuming we know where that
-  is. More important, debugging statements stay with the program;
-  debugging sessions are transient.
-

-

Logging does have its drawbacks. It can slow down an application. If too verbose, it can cause scrolling blindness. To -alleviate these concerns, log4j is designed to be reliable, fast and +alleviate these concerns, log4cxx is designed to be reliable, fast and extensible. Since logging is rarely the main focus of an application, -the log4j API strives to be simple to understand and to use.

+the log4cxx API strives to be simple to understand and to use.

Loggers, Appenders and Layouts

-

Log4j has three main components: loggers, +

Log4cxx has three main components: loggers, appenders and layouts. These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these @@ -259,16 +224,11 @@

Logger hierarchy

The first and foremost advantage of any logging API over plain -System.out.println resides in its ability to disable +std::cout resides in its ability to disable certain log statements while allowing others to print unhindered. This capability assumes that the logging space, that is, the space of all possible logging statements, is categorized according to some -developer-chosen criteria. This observation had previously led us to -choose category as the central concept of the -package. However, since log4j version 1.2, Logger class -has replaced the Category class. For those familiar with -earlier versions of log4j, the Logger class can be -considered as a mere alias to the Category class.

+developer-chosen criteria.

Loggers are named entities. Logger names are case-sensitive and they follow the hierarchical naming rule:

@@ -304,9 +264,9 @@
  • it always exists,
  • it cannot be retrieved by name.
  • -Invoking the class static Logger.getRootLogger +Invoking the class static log4cxx::Logger::getRootLogger method retrieves it. All other loggers are instantiated and -retrieved with the class static Logger.getLogger +retrieved with the class static log4cxx::Logger::getLogger method. This method takes the name of the desired logger as a parameter. Some of the basic methods in the Logger class are listed below. @@ -315,45 +275,35 @@
    -  package org.apache.log4j;
    -
    -  public class Logger {
    +  namespace log4cxx {
     
    -    // Creation & retrieval methods:
    -    public static Logger getRootLogger();
    -    public static Logger getLogger(String name);
    -
    -    // printing methods:
    -    public void trace(Object message);
    -    public void debug(Object message);
    -    public void info(Object message);
    -    public void warn(Object message);
    -    public void error(Object message);
    -    public void fatal(Object message);
    +    class Logger {
    +       public:
    +       // Creation & retrieval methods:
    +       static LoggerPtr getRootLogger();
    +       static LoggerPtr getLogger(const std::string& name);
    +       static LoggerPtr getLogger(const std::wstring& name);
     
    -    // generic printing method:
    -    public void log(Level l, Object message);
    -}
    +     }
    +   }
    +//
    +//   Use these macros instead of calling Logger methods directly.
    +//   Macros will accept char and wchar_t pointers and strings.
    +//   
    +#define LOG4CXX_TRACE(logger, msg) ...   
    +#define LOG4CXX_DEBUG(logger, msg) ...   
    +#define LOG4CXX_INFO(logger, msg) ...   
    +#define LOG4CXX_WARN(logger, msg) ...   
    +#define LOG4CXX_ERROR(logger, msg) ...   
    +#define LOG4CXX_FATAL(logger, msg) ...   
     

    -

    Loggers may be assigned levels. The set of possible -levels, that is:



    - -TRACE,

    -DEBUG,

    -INFO,

    -WARN,

    -ERROR and

    -FATAL

    -

    - -are defined in the org.apache.log4j.Level -class. Although we do not encourage you to do so, you may define -your own levels by sub-classing the Level class. A -perhaps better approach will be explained later on.

    +

    Loggers may be assigned levels. The pre-defined +levels: TRACE, DEBUG, INFO, WARN, ERROR and FATAL are defined in the log4cxx::Level +class which provides accessor functions.

    If a given logger is not assigned a level, then it inherits one from its closest ancestor with an assigned level. More @@ -447,24 +397,9 @@ having an assigned level..

    -

    Logging requests are made by invoking one of the printing methods -of a logger instance. These printing methods are - - -debug, - -info, - -warn, -error, -fatal - and log.

    - - -

    By definition, the printing method determines the level of a -logging request. For example, if c is a logger -instance, then the statement c.info("..") is a logging -request of level INFO.

    +

    Logging requests are made by invoking a method of +a logger instance, preferrably through the use of LOG4CXX_INFO or similar +macros. Each request specifies the level of the logging request.

    A logging request is said to be enabled if its level is higher than or equal to the level of its logger. Otherwise, the @@ -486,8 +421,8 @@

    -

    This rule is at the heart of log4j. It assumes that levels are -ordered. For the standard levels, we have DEBUG < INFO +

    This rule is at the heart of log4cxx. It assumes that levels are +ordered. For the standard levels, we have TRACE < DEBUG < INFO < WARN < ERROR < FATAL.

    Here is an example of this rule.

    @@ -497,29 +432,29 @@
     
        // get a logger instance named "com.foo"
    -   Logger  logger = Logger.getLogger("com.foo");
    +   log4cxx::LoggerPtr  logger(log4cxx::Logger::getLogger("com.foo"));
     
        // Now set its level. Normally you do not need to set the
        // level of a logger programmatically. This is usually done
        // in configuration files.
    -   logger.setLevel(Level.INFO);
    +   logger->setLevel(log4cxx::Level::getInfo());
     
    -   Logger barlogger = Logger.getLogger("com.foo.Bar");
    +   log4cxx::LoggerPtr barlogger(log4cxx::Logger::getLogger("com.foo.Bar");
     
        // This request is enabled, because WARN >= INFO.
    -   logger.warn("Low fuel level.");
    +   LOG4CXX_WARN(logger, "Low fuel level.");
     
        // This request is disabled, because DEBUG < INFO.
    -   logger.debug("Starting search for nearest gas station.");
    +   LOG4CXX_DEBUG(logger, "Starting search for nearest gas station.");
     
        // The logger instance barlogger, named "com.foo.Bar",
        // will inherit its level from the logger named
        // "com.foo" Thus, the following request is enabled
        // because INFO >= INFO.
    -   barlogger.info("Located nearest gas station.");
    +   LOG4CXX_INFO(barlogger. "Located nearest gas station.");
     
        // This request is disabled, because DEBUG < INFO.
    -   barlogger.debug("Exiting gas station search");
    +   LOG4CXX_DEBUG(barlogger, "Exiting gas station search");
     

    @@ -532,8 +467,8 @@
    -   Logger x = Logger.getLogger("wombat");
    -   Logger y = Logger.getLogger("wombat");
    + log4cxx::LoggerPtr x = log4cxx::Logger::getLogger("wombat"); + log4cxx::LoggerPtr y = log4cxx::Logger::getLogger("wombat");
    x and y refer to exactly the same @@ -542,23 +477,23 @@

    Thus, it is possible to configure a logger and then to retrieve the same instance somewhere else in the code without passing around references. In fundamental contradiction to biological parenthood, -where parents always preceed their children, log4j loggers can be +where parents always preceed their children, log4cxx loggers can be created and configured in any order. In particular, a "parent" logger will find and link to its descendants even if it is instantiated after them.

    -

    Configuration of the log4j environment is typically done at +

    Configuration of the log4cxx environment is typically done at application initialization. The preferred way is by reading a configuration file. This approach will be discussed shortly.

    -

    Log4j makes it easy to name loggers by software +

    Log4cxx makes it easy to name loggers by software component. This can be accomplished by statically instantiating a logger in each class, with the logger name equal to the fully qualified name of the class. This is a useful and straightforward method of defining loggers. As the log output bears the name of the generating logger, this naming strategy makes it easy to identify the origin of a log message. However, this is only one possible, -albeit common, strategy for naming loggers. Log4j does not restrict +albeit common, strategy for naming loggers. Log4cxx does not restrict the possible set of loggers. The developer is free to name the loggers as desired.

    @@ -568,20 +503,18 @@

    Appenders and Layouts

    The ability to selectively enable or disable logging requests based -on their logger is only part of the picture. Log4j allows logging -requests to print to multiple destinations. In log4j speak, an output +on their logger is only part of the picture. Log4cxx allows logging +requests to print to multiple destinations. In log4cxx speak, an output destination is called an appender. Currently, appenders exist -for the console, files, GUI -components, remote socket -servers, JMS, - - NT -Event Loggers, and remote UNIX Syslog -daemons. It is also possible to log asynchronously.

    +for the console, files, GUI +components, remote socket +servers, NT +Event Loggers, and remote UNIX Syslog +daemons. It is also possible to log asynchronously.

    More than one appender can be attached to a logger.

    -

    The addAppender +

    The addAppender method adds an appender to a given logger. Each enabled logging @@ -594,7 +527,7 @@ C, then enabled logging requests for C and C's children will print on a file and on the console. It is possible to override this default behavior so that -appender accumulation is no longer additive by setting +appender accumulation is no longer additive by setting the additivity flag to false.

    The rules governing appender additivity are summarized below.

    @@ -631,7 +564,7 @@ root A1 not applicable A1 The root logger is anonymous but can be accessed with the - Logger.getRootLogger() method. There is no default appender + log4cxx::Logger::getRootLogger() method. There is no default appender attached to root. x A-x1, A-x2 true A1, A-x1, A-x2 @@ -663,8 +596,8 @@ wishes, whereas an appender takes care of sending the formatted output to its destination.

    -The PatternLayout, part -of the standard log4j distribution, lets the user specify the output +The PatternLayout, part +of the standard log4cxx distribution, lets the user specify the output format according to conversion patterns similar to the C language printf function.

    @@ -681,23 +614,6 @@ fourth field is the name of the logger associated with the log request. The text after the '-' is the message of the statement.

    -

    Just as importantly, log4j will render the content of the log -message according to user specified criteria. For example, if you -frequently need to log Oranges, an object type used in -your current project, then you can register an -OrangeRenderer that will be invoked whenever an orange -needs to be logged.

    - -

    Object rendering follows the class hierarchy. For example, assuming -oranges are fruits, if you register an FruitRenderer, all -fruits including oranges will be rendered by the -FruitRenderer, unless of course you registered an orange -specific OrangeRenderer.

    - -

    Object renderers have to implement the -ObjectRenderer -interface.

    -

    Configuration

    @@ -708,105 +624,110 @@ within their code. Given their number, it becomes imperative to manage these log statements without the need to modify them manually.

    -

    The log4j environment is fully configurable programmatically. -However, it is far more flexible to configure log4j using +

    The log4cxx environment is fully configurable programmatically. +However, it is far more flexible to configure log4cxx using configuration files. Currently, configuration files can be written in XML or in Java properties (key=value) format.

    Let us give a taste of how this is done with the help of an -imaginary application MyApp that uses log4j.

    +imaginary application MyApp that uses log4cxx.

    - import com.foo.Bar;
    -
    - // Import log4j classes.
    - import org.apache.log4j.Logger;
    - import org.apache.log4j.BasicConfigurator;
    -
    - public class MyApp {
    -
    -   // Define a static logger variable so that it references the
    -   // Logger instance named "MyApp".
    -   static Logger logger = Logger.getLogger(MyApp.class);
    +#include "com/foo/bar.h"
    +using namespace com::foo;
     
    -   public static void main(String[] args) {
    +// include log4cxx header files.
    +#include "log4cxx/logger.h"
    +#include "log4cxx/basicconfigurator.h"
    +#include "log4cxx/helpers/exception.h"
    +
    +using namespace log4cxx;
    +using namespace log4cxx::helpers;
    +
    +LoggerPtr logger(Logger::getLogger("MyApp"));
    +
    +int main(int argc, char **argv)
    +{
    +        int result = EXIT_SUCCESS;
    +        try
    +        {
    +                // Set up a simple configuration that logs on the console.
    +                BasicConfigurator::configure();
    +
    +                LOG4CXX_INFO(logger, "Entering application.");
    +                Bar bar;
    +                bar.doIt();
    +                LOG4CXX_INFO(logger, "Exiting application.");
    +        }
    +        catch(Exception&)
    +        {
    +                result = EXIT_FAILURE;
    +        }
     
    -     // Set up a simple configuration that logs on the console.
    -     BasicConfigurator.configure();
    -
    -     logger.info("Entering application.");
    -     Bar bar = new Bar();
    -     bar.doIt();
    -     logger.info("Exiting application.");
    -   }
    - }
    +        return result;
    +}
     

    -

    MyApp begins by importing log4j related classes. It +

    MyApp begins by including log4cxx headers. It then defines a static logger variable with the name MyApp which happens to be the fully qualified name of the class.

    -

    MyApp uses the Bar class defined in the -package com.foo.

    +

    MyApp uses the Bar class defined in header +file com/foo/bar.h.

    - package com.foo;
    - import org.apache.log4j.Logger;
    +//  file com/foo/bar.h
    +#include "log4cxx/logger.h"
     
    - public class Bar {
    -   static Logger logger = Logger.getLogger(Bar.class);
    +namespace com {
    +   namespace foo {
    +      class Bar {
    +          static log4cxx::LoggerPtr logger;
    +          
    +      public:
    +          void doIt();
    +       }
    +    }
    +}
    +
    - public void doIt() { - logger.debug("Did it again!"); - } - } +
    +// file bar.cpp
    +#include "com/foo/bar.h"
    +
    +using namespace com::foo;
    +using namespace log4cxx;
    +
    +LoggerPtr Bar::logger(Logger::getLogger("com.foo.bar"));
    +
    +void Bar::doIt() {
    +   LOG4CXX_DEBUG(logger, "Did it again!");
    +}
     

    -

    The invocation of the BasicConfigurator.configure -method creates a rather simple log4j setup. This method is hardwired -to add to the root logger a -ConsoleAppender. The output will be formatted using a PatternLayout set +

    The invocation of the BasicConfigurator::configure +method creates a rather simple log4cxx setup. This method is hardwired +to add to the root logger a +ConsoleAppender. The output will be formatted using a PatternLayout set to the pattern "%-4r [%t] %-5p %c %x - %m%n".

    Note that by default, the root logger is assigned to -Level.DEBUG.

    +Level::getDebug().

    The output of MyApp is:

    -0    [main] INFO  MyApp  - Entering application.
    -36   [main] DEBUG com.foo.Bar  - Did it again!
    -51   [main] INFO  MyApp  - Exiting application.
    +0    [12345] INFO  MyApp  - Entering application.
    +36   [12345] DEBUG com.foo.Bar  - Did it again!
    +51   [12345] INFO  MyApp  - Exiting application.
     

    -

    The figure below depicts the object diagram of MyApp -after just having called the BasicConfigurator.configure -method.

    - -

    -

    - -

    - -

    As a side note, let me mention that in log4j child loggers link -only to their existing ancestors. In particular, the logger named -com.foo.Bar is linked directly to the root -logger, thereby circumventing the unused com or -com.foo loggers. This significantly increases -performance and reduces log4j's memory footprint.

    - - -

    The MyApp class configures log4j by invoking -BasicConfigurator.configure method. Other classes only -need to import the org.apache.log4j.Logger class, -retrieve the loggers they wish to use, and log away.

    -

    The previous example always outputs the same log information. Fortunately, it is easy to modify MyApp so that the log output can be controlled at run-time. Here is a slightly modified @@ -814,27 +735,50 @@

    - import com.foo.Bar;
    -
    - import org.apache.log4j.Logger;
    - import org.apache.log4j.PropertyConfigurator;
    -
    - public class MyApp {
    -
    -   static Logger logger = Logger.getLogger(MyApp.class.getName());
    +// file MyApp2.cpp
     
    -   public static void main(String[] args) {
    +#include "com/foo/bar.h"
    +using namespace com::foo;
     
    +// include log4cxx header files.
    +#include "log4cxx/logger.h"
    +#include "log4cxx/basicconfigurator.h"
    +#include "log4cxx/propertyconfigurator.h"
    +#include "log4cxx/helpers/exception.h"
    +
    +using namespace log4cxx;
    +using namespace log4cxx::helpers;
    +// Define a static logger variable so that it references the
    +// Logger instance named "MyApp".
    +LoggerPtr logger(Logger::getLogger("MyApp"));
    +
    +int main(int argc, char **argv)
    +{
    +        int result = EXIT_SUCCESS;
    +        try
    +        {
    +                if (argc > 1)
    +                {
    +                        // BasicConfigurator replaced with PropertyConfigurator.
    +                        PropertyConfigurator::configure(argv[1]);
    +                }
    +                else
    +                {
    +                        BasicConfigurator::configure();
    +                }
    +
    +                LOG4CXX_INFO(logger, "Entering application.");
    +                Bar bar
    +                bar.doIt();
    +                LOG4CXX_INFO(logger, "Exiting application.");
    +        }
    +        catch(Exception&)
    +        {
    +                result = EXIT_FAILURE;
    +        }
     
    -     // BasicConfigurator replaced with PropertyConfigurator.
    -     PropertyConfigurator.configure(args[0]);
    -
    -     logger.info("Entering application.");
    -     Bar bar = new Bar();
    -     bar.doIt();
    -     logger.info("Exiting application.");
    -   }
    - }
    +        return result;
    +}
     
    @@ -860,9 +804,10 @@

    +

    It can be noticed that the PropertyConfigurator file format is the same as log4j.

    Suppose we are no longer interested in seeing the output of any -component belonging to the com.foo package. The following +component belonging to the com::foo package. The following configuration file shows one possible way of achieving this.

    @@ -882,14 +827,14 @@

    The output of MyApp configured with this file is shown below.

    -2000-09-07 14:07:41,508 [main] INFO  MyApp - Entering application.
    -2000-09-07 14:07:41,529 [main] INFO  MyApp - Exiting application.
    +2000-09-07 14:07:41,508 [12345] INFO  MyApp - Entering application.
    +2000-09-07 14:07:41,529 [12345] INFO  MyApp - Exiting application.
     

    As the logger com.foo.Bar does not have an assigned level, it inherits its level from com.foo, which was set to WARN in the configuration file. The log statement from the -Bar.doIt method has the level DEBUG, lower than the +Bar::doIt method has the level DEBUG, lower than the logger level WARN. Consequently, doIt() method's log request is suppressed.

    @@ -921,9 +866,9 @@ output the following on the console.

    - INFO [main] (MyApp2.java:12) - Entering application.
    -DEBUG [main] (Bar.java:8) - Doing it again!
    - INFO [main] (MyApp2.java:15) - Exiting application.
    + INFO [12345] (MyApp2.cpp:31) - Entering application.
    +DEBUG [12345] (Bar.h:16) - Doing it again!
    + INFO [12345] (MyApp2.cpp:34) - Exiting application.
     

    In addition, as the root logger has been allocated a second @@ -935,218 +880,42 @@

    Note that to obtain these different logging behaviors we did not need to recompile code. We could just as easily have logged to a UNIX Syslog daemon, redirected all com.foo output to an NT -Event logger, or forwarded logging events to a remote log4j server, +Event logger, or forwarded logging events to a remote log4cxx server, which would log according to local server policy, for example by -forwarding the log event to a second log4j server.

    +forwarding the log event to a second log4cxx server.

    Default Initialization Procedure

    -

    The log4j library does not make any assumptions about its -environment. In particular, there are no default log4j +

    The log4cxx library does not make any assumptions about its +environment. In particular, there are no default log4cxx appenders. Under certain well-defined circumstances however, the static inializer of the Logger class will attempt to -automatically configure log4j. The Java language guarantees that the -static initializer of a class is called once and only once during the -loading of a class into memory. It is important to remember that -different classloaders may load distinct copies of the same -class. These copies of the same class are considered as totally -unrelated by the JVM.

    - -

    The default initialization is very useful in environments where the -exact entry point to the application depends on the runtime -environment. For example, the same application can be used as a -stand-alone application, as an applet, or as a servlet under the -control of a web-server.

    +automatically configure log4cxx.

    The exact default initialization algorithm is defined as follows:

      -
    1. Setting the log4j.defaultInitOverride system property to - any other value then "false" will cause log4j to skip the default - initialization procedure (this procedure).
    2. - -
    3. Set the resource string variable to the value of - the log4j.configuration system property. The preferred - way to specify the default initialization file is through the - log4j.configuration system property. In case the system - property log4j.configuration is not defined, then set the - string variable resource to its default value - "log4j.properties".
    4. - -
    5. Attempt to convert the resource variable to a - URL.
    6. - -
    7. If the resource variable cannot be converted to a URL, for - example due to a MalformedURLException, then search for - the resource from the classpath by calling - org.apache.log4j.helpers.Loader.getResource(resource, - Logger.class) which returns a URL. Note that the string - "log4j.properties" constitutes a malformed URL. - - See Loader.getResource(java.lang.String) - for the list of searched locations.
    8. - -
    9. If no URL could not be found, abort default - initialization. Otherwise, configure log4j from the URL. - - The PropertyConfigurator - will be used to parse the URL to configure log4j unless the URL ends - with the ".xml" extension, in which case the DOMConfigurator - will be used. You can optionaly specify a custom configurator. The - value of the log4j.configuratorClass system property is taken - as the fully qualified class name of your custom configurator. The - custom configurator you specify must implement the Configurator - interface.
    10. +
    11. Set the configurationOptionStr string variable to the value of the + LOG4CXX_CONFIGURATION environment variable if set, otherwise + the value of the log4j.configuration environment variable if set, + otherwise the first of the following file names which exist in the + current working directory, "log4cxx.properties", "log4j.properties", + "log4cxx.xml" and "log4j.xml". + If configurationOptionStr has not been set, then disable logging. + +

      Unless a custom configurator is specified using the + LOG4CXX_CONFIGURATOR_CLASS or log4j.configuratorClass + environment variable, the PropertyConfigurator will be used to configure + log4cxx unless the file name ends with the ".xml" extension, + in which case the DOMConfigurator will be used. + If a custom configurator is specified, the environment variable + should contain a fully qualified class name of a class that + implements the Configurator interface.

      +
    -

    Example Configurations

    - - - -

    Default Initialization under Tomcat

    - -The default log4j initialization is particularly useful in -web-server environments. Under Tomcat 3.x and 4.x, you should place -the log4j.properties under the -WEB-INF/classes directory of your web-applications. Log4j -will find the properties file and initialize itself. This is easy to -do and it works. - -You can also choose to set the system property -log4j.configuration before starting Tomcat. For Tomcat 3.x The -TOMCAT_OPTS environment variable is used to set command -line options. For Tomcat 4.0, set the CATALINA_OPTS -environment variable instead of TOMCAT_OPTS. - -Example 1 - -

    The Unix shell command -

    -   export TOMCAT_OPTS="-Dlog4j.configuration=foobar.txt"
    -
    - -tells log4j to use the file foobar.txt as the default -configuration file. This file should be place under the -WEB-INF/classes directory of your web-application. The -file will be read using the PropertyConfigurator. Each -web-application will use a different default configuration file because -each file is relative to a web-application.

    - - -

    Example 2

    - -

    The Unix shell command -

    -   export TOMCAT_OPTS="-Dlog4j.debug -Dlog4j.configuration=foobar.xml"
    -
    - -tells log4j to output log4j-internal debugging information and to use -the file foobar.xml as the default configuration -file. This file should be place under the WEB-INF/classes -directory of your web-application. Since the file ends with a -.xml extension, it will read using the DOMConfigurator. Each -web-application will use a different default configuration file because -each file is relative to a web-application.

    - -

    Example 3

    - -

    The Windows shell command -

    -   set TOMCAT_OPTS=-Dlog4j.configuration=foobar.lcf -Dlog4j.configuratorClass=com.foo.BarConfigurator
    -
    - -tells log4j to use the file foobar.lcf as the default -configuration file. This file should be place under the -WEB-INF/classes directory of your web-application. Due to -the definition of the log4j.configuratorClass system property, -the file will be read using the com.foo.BarConfigurator -custom configurator. Each web-application will use a different -default configuration file because each file is relative to a -web-application.

    - -

    Example 4

    - -

    The Windows shell command -

    -   set TOMCAT_OPTS=-Dlog4j.configuration=file:/c:/foobar.lcf
    - -tells log4j to use the file c:\foobar.lcf as the default -configuration file. The configuration file is fully specified by the -URL file:/c:/foobar.lcf. Thus, the same configuration -file will be used for all web-applications.

    - - -

    Different web-applications will load the log4j classes through -their respective classloaderss. Thus, each image of the log4j -environment will act independetly and without any mutual -synchronization. For example, FileAppenders defined -exactly the same way in multiple web-application configurations will -all attempt to write the same file. The results are likely to be less -than satisfactory. You must make sure that log4j configurations of -different web-applications do not use the same underlying system -resource.

    - - -

    Initialization servlet

    - -

    It is also possible to use a special servlet for log4j -initialization. Here is an example,

    - -

    -
    -package com.foo;
    -
    -import org.apache.log4j.PropertyConfigurator;
    -import javax.servlet.http.HttpServlet;
    -import javax.servlet.http.HttpServletRequest;
    -import javax.servlet.http.HttpServletResponse;
    -import java.io.PrintWriter;
    -import java.io.IOException;
    -
    -public class Log4jInit extends HttpServlet {
    -
    -  public
    -  void init() {
    -    String prefix =  getServletContext().getRealPath("/");
    -    String file = getInitParameter("log4j-init-file");
    -    // if the log4j-init-file is not set, then no point in trying
    -    if(file != null) {
    -      PropertyConfigurator.configure(prefix+file);
    -    }
    -  }
    -
    -  public
    -  void doGet(HttpServletRequest req, HttpServletResponse res) {
    -  }
    -}
    -
    -

    - -

    Define the following servlet in the web.xml file for your web-application.

    - -

    -
    -  <servlet>
    -    <servlet-name>log4j-init</servlet-name>
    -    <servlet-class>com.foo.Log4jInit</servlet-class>
    -
    -    <init-param>
    -      <param-name>log4j-init-file</param-name>
    -      <param-value>WEB-INF/classes/log4j.lcf</param-value>
    -    </init-param>
    -
    -    <load-on-startup>1</load-on-startup>
    -  </servlet>
    -
    -

    - -

    Writing an initialization servlet is the most flexible way for -initializing log4j. There are no constraints on the code you can place -in the init() method of the servlet.

    - -

    Nested Diagnostic Contexts

    @@ -1172,25 +941,28 @@ Nested Diagnostic Context. The NDC class is shown below.
    -  public class NDC {
    +namespace log4cxx {
    +  class NDC {
    +  public:
         // Used when printing the diagnostic
    -    public static String get();
    +    static LogString get();
     
         // Remove the top of the context from the NDC.
    -    public static String pop();
    +    static LogString pop();
     
         // Add diagnostic context for the current thread.
    -    public static void push(String message);
    +    static void push(const std::string& message);
    +    static void push(const std::wstring& message);
     
         // Remove the diagnostic context for this thread.
    -    public static void remove();
    +    static void remove();
       }
     

    The NDC is managed per thread as a stack of contextual -information. Note that all methods of the org.apache.log4j.NDC +information. Note that all methods of the log4cxx::NDC class are static. Assuming that NDC printing is turned on, every time -a log request is made, the appropriate log4j component will include +a log request is made, the appropriate log4cxx component will include the entire NDC stack for the current thread in the log output. This is done without the intervention of the user, who is responsible only for placing the correct information in the NDC by @@ -1213,7 +985,7 @@

    Nevertheless, some sophisticated applications, such as virtual hosting web servers, must log differently depending on the virtual host context and also depending on the software component issuing the -request. Recent log4j releases support multiple hierarchy trees. This +request. Recent log4cxx releases support multiple hierarchy trees. This enhancement allows each virtual host to possess its own copy of the logger hierarchy.

    @@ -1223,7 +995,7 @@

    One of the often-cited arguments against logging is its computational cost. This is a legitimate concern as even moderately sized applications can generate thousands of log requests. Much -effort was spent measuring and tweaking logging performance. Log4j +effort was spent measuring and tweaking logging performance. Log4cxx claims to be fast and flexible: speed first, flexibility second.

    The user should be aware of the following performance issues.

    @@ -1232,57 +1004,11 @@
  • Logging performance when logging is turned off.

    When logging is turned - off entirely or just for a set + off entirely or just for a set of levels, the cost of a log request consists of a method - invocation plus an integer comparison. On a 233 MHz Pentium II - machine this cost is typically in the 5 to 50 nanosecond range. - -

    However, The method invocation involves the "hidden" cost of - parameter construction.

    - -

    For example, for some logger cat, writing, -

    -     logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
    -    
    - - incurs the cost of constructing the message parameter, i.e. - converting both integer i and entry[i] - to a String, and concatenating intermediate strings, - regardless of whether the message will be logged or not. - - This cost of parameter construction can be quite high and it - depends on the size of the parameters involved.

    - - -

    To avoid the parameter construction cost write: -

    -      if(logger.isDebugEnabled() {
    -        logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
    -      }
    -   

    - -

    This will not incur the cost of parameter - construction if debugging is disabled. On the other hand, if - the logger is debug-enabled, it will incur twice the cost of - evaluating whether the logger is enabled or not: once - in debugEnabled and once in - debug. This is an insignificant - overhead because evaluating a logger takes about 1% - of the time it takes to actually log.

    - -

    In log4j, logging requests are made to instances of the Logger - class. Logger is a class and not an interface. This measurably - reduces the cost of method invocation at the cost of some - flexibility.

    - - -

    Certain users resort to preprocessing or compile-time - techniques to compile out all log statements. This leads to perfect - performance efficiency with respect to logging. However, since the - resulting application binary does not contain any log statements, - logging cannot be turned on for that binary. In my opinion this is - a disproportionate price to pay in exchange for a small performance - gain.

  • + invocation plus an integer comparison. The LOG4CXX_DEBUG and similar + macros suppress unnecessary expression evaluation if the + request is not enabled.
  • The performance of deciding whether to log or not to log when logging is turned on.

    @@ -1312,48 +1038,36 @@ This is the cost of formatting the log output and sending it to its target destination. Here again, a serious effort was made to make layouts (formatters) perform as quickly as possible. The same - is true for appenders. The typical cost of actually logging is - about 100 to 300 microseconds. + is true for appenders. - See org.apache.log4.performance.Logging - for actual figures.
  • -

    Although log4j has many features, its first design goal was speed. -Some log4j components have been rewritten many times to improve +

    Although log4cxx has many features, its first design goal was speed. +Some log4cxx components have been rewritten many times to improve performance. Nevertheless, contributors frequently come up with new optimizations. You should be pleased to know that when configured with -the SimpleLayout +the SimpleLayout performance tests have shown log4j to log as quickly as -System.out.println.

    +std::cout.

    Conclusions

    -

    Log4j is a popular logging package written in Java. One of its +

    Log4cxx is a popular logging package written in C++. One of its distinctive features is the notion of inheritance in loggers. Using a logger hierarchy it is possible to control which log statements are output at arbitrary granularity. This helps reduce the volume of logged output and minimize the cost of logging.

    -

    One of the advantages of the log4j API is its manageability. Once +

    One of the advantages of the log4cxx API is its manageability. Once the log statements have been inserted into the code, they can be controlled with configuration files. They can be selectively enabled or disabled, and sent to different and multiple output targets in -user-chosen formats. The log4j package is designed so that log +user-chosen formats. The log4cxx package is designed so that log statements can remain in shipped code without incurring a heavy performance cost.

    -

    Acknowledgments

    - -Many thanks to N. Asokan for reviewing the article. He is also one of -the originators of the logger concept. I am indebted to Nelson Minar -for encouraging me to write this article. He has also made many useful -suggestions and corrections to this article. Log4j is the result of a -collective effort. My special thanks go to all the authors who have -contributed to the project. Without exception, the best features in -the package have all originated in the user community. Modified: logging/site/trunk/docs/log4cxx/news.html URL: http://svn.apache.org/viewvc/logging/site/trunk/docs/log4cxx/news.html?view=diff&rev=564410&r1=564409&r2=564410 ============================================================================== --- logging/site/trunk/docs/log4cxx/news.html (original) +++ logging/site/trunk/docs/log4cxx/news.html Thu Aug 9 15:34:47 2007 @@ -43,7 +43,7 @@
    - Last Published: 07/24/2007 + Last Published: 08/06/2007 | Apache > Modified: logging/site/trunk/docs/log4cxx/performance.html URL: http://svn.apache.org/viewvc/logging/site/trunk/docs/log4cxx/performance.html?view=diff&rev=564410&r1=564409&r2=564410 ============================================================================== --- logging/site/trunk/docs/log4cxx/performance.html (original) +++ logging/site/trunk/docs/log4cxx/performance.html Thu Aug 9 15:34:47 2007 @@ -43,7 +43,7 @@
    - Last Published: 07/24/2007 + Last Published: 08/06/2007 | Apache > Modified: logging/site/trunk/docs/log4cxx/project-info.html URL: http://svn.apache.org/viewvc/logging/site/trunk/docs/log4cxx/project-info.html?view=diff&rev=564410&r1=564409&r2=564410 ============================================================================== --- logging/site/trunk/docs/log4cxx/project-info.html (original) +++ logging/site/trunk/docs/log4cxx/project-info.html Thu Aug 9 15:34:47 2007 @@ -40,7 +40,7 @@
    - Last Published: 07/24/2007 + Last Published: 08/09/2007 | Apache > @@ -167,7 +167,7 @@
    -

    Project Information

    This document provides an overview of the various documents and links that are part of this project's general information. All of this content is automatically generated by Maven on behalf of the project.

    Overview

    DocumentDescription
    DependenciesThis document lists the projects dependencies and provides information on each dependency.
    Mailing ListsThis document provides subscription and archive information for this project's mailing lists.
    Issue TrackingThis is a link to the issue management system for this project. Issues (bugs, features, change requests) can be created and queried using this li nk.
    Source RepositoryThis is a link to the online source repository that can be viewed via a web browser.
    Project LicenseThis is a link to the definitions of project licenses.
    +

    Project Information

    This document provides an overview of the various documents and links that are part of this project's general information. All of this content is automatically generated by Maven on behalf of the project.

    Overview

    DocumentDescription
    Project LicenseThis is a link to the definitions of project licenses.
    DependenciesThis document lists the projects dependencies and provides information on each dependency.
    Mailing ListsThis document provides subscription and archive information for this project's mailing lists.
    Source RepositoryThis i s a link to the online source repository that can be viewed via a web browser.
    Issue TrackingThis is a link to the issue management system for this project. Issues (bugs, features, change requests) can be created and queried using this link.
    Modified: logging/site/trunk/docs/log4cxx/project-reports.html URL: http://svn.apache.org/viewvc/logging/site/trunk/docs/log4cxx/project-reports.html?view=diff&rev=564410&r1=564409&r2=564410 ============================================================================== --- logging/site/trunk/docs/log4cxx/project-reports.html (original) +++ logging/site/trunk/docs/log4cxx/project-reports.html Thu Aug 9 15:34:47 2007 @@ -40,7 +40,7 @@
    - Last Published: 07/24/2007 + Last Published: 08/09/2007 | Apache > Modified: logging/site/trunk/docs/log4cxx/roadmap.html URL: http://svn.apache.org/viewvc/logging/site/trunk/docs/log4cxx/roadmap.html?view=diff&rev=564410&r1=564409&r2=564410 ============================================================================== --- logging/site/trunk/docs/log4cxx/roadmap.html (original) +++ logging/site/trunk/docs/log4cxx/roadmap.html Thu Aug 9 15:34:47 2007 @@ -40,7 +40,7 @@
    - Last Published: 07/24/2007 + Last Published: 08/06/2007 | Apache > Modified: logging/site/trunk/docs/log4cxx/source-repository.html URL: http://svn.apache.org/viewvc/logging/site/trunk/docs/log4cxx/source-repository.html?view=diff&rev=564410&r1=564409&r2=564410 ============================================================================== --- logging/site/trunk/docs/log4cxx/source-repository.html (original) +++ logging/site/trunk/docs/log4cxx/source-repository.html Thu Aug 9 15:34:47 2007 @@ -40,7 +40,7 @@
    - Last Published: 07/24/2007 + Last Published: 08/09/2007 | Apache > Modified: logging/site/trunk/docs/log4cxx/stylesheets/project.html URL: http://svn.apache.org/viewvc/logging/site/trunk/docs/log4cxx/stylesheets/project.html?view=diff&rev=564410&r1=564409&r2=564410 ============================================================================== --- logging/site/trunk/docs/log4cxx/stylesheets/project.html (original) +++ logging/site/trunk/docs/log4cxx/stylesheets/project.html Thu Aug 9 15:34:47 2007 @@ -40,7 +40,7 @@
    - Last Published: 07/24/2007 + Last Published: 08/06/2007 | Apache >