Hi Ceki, Here is the file traducted until the first "level hierarchy" table.
Ionel
Vous manquez d�espace pour stocker vos mails ?
Yahoo! Mail vous offre GRATUITEMENT 100 Mo !
Cr�ez votre Yahoo! Mail sur http://fr.benefits.yahoo.com/
Le nouveau Yahoo! Messenger est arriv� ! D�couvrez toutes les nouveaut�s pour
dialoguer instantan�ment avec vos amis. A t�l�charger gratuitement sur
http://fr.messenger.yahoo.comTitle: Manuel d'utilisation - log4j
Petit manuel d'utilisation de log4jCeki GülcüMarch 2002 Ionel Gardais Traduction Août 2004 Copyright © 2000-2002 The Apache Software Foundation. Tous droits r�serv�s rights reserved. This software is published under the terms of the Apache Software License version 1.1, a copy of which has been included in the LICENSE.txt 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). R�sum�Ce document d�crit l'API log4j, ces composants ainsi que son architecture. Log4j est un projet open source d�velopp� par de nombreuses personnes. Il permet au developpeur de controler quelles notes seront sauvegard�es avec leur propre d�finition. Log4j est enti�rement configurable via l'utilisation d'un fichier de configuration externe. De plus, il est tr�s simple d'apprendre � utiliser log4j. Mais attention : d'apr�s les remarques des differents utilisateurs, on devient vite accro. IntroductionPresque toutes les applications de grande envergure disposent d'une API de journalisation ou de tracage. En s'appuyant sur ce principe, le projet europ�en SEMPER a d�cid� d'�crire sa propre API de tracage. C'�tait au d�but de l'ann�e 1996. Apr�s de nombreuses �volutions, plusieurs changement de chef de projet et beaucoup de travail cette API a �volu� pour devenir log4j, un package Java bien connu pour la journalisation. Ce package est distribu� sous couvert de la licence "Apache Software License", licence open source valid�e par les "instances" open source. La derni�re version de log4j, incluant l'ensemble du code source, les classes Java ainsi que la documentation peut �tre r�cup�r�e � http://jakarta.apache.org/log4j/. Pour info, log4j a �t� port� pour les languages C, C++, C#, Perl, Python, Ruby et Eiffel. Inserer des appels de journalisation dans le code est une technique de d�boggage bas-niveau. Il se peut que ce soit aussi la seule methode possible lorsque l'on n'en dispose pas ou que son utilisation est impossible. C'est souvent le cas pour les applications multi-thread�s ou distribu�s. L'experience montre que la journalisation est un point important dans le cycle de d�veloppement. Elle offre divers avantages. Elle fournit une donn�e pr�cise sue le context d'execution d'une application. Une fois int�gr�e au code, la g�n�ration d'une note ne necessite pas d'intervention humaine. De plus, la note peut �tre sauvegard�e sur un support physique pour �tre �tudi�e plus tard. Outre son utilisation dans le cycle de developpement, un package de journalisation peut aussi �tre consid�r� comme un outil d'audit. Comme l'indique Brian W. Kernighan et Rob Pike dans leur excellent livre "The Practice of Programming" (titre original) 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. La journalisation a cependant ces d�fauts. Elle peut ralentir une application. Si elle est trop loquace, vous deviendrez vite aveugle � force de tenter de lire les lignes qui defilent � toute allure. Pour minimiser ces points, log4j est con�u pour �tre fiable, rapide et extentsible. Vu que la journalisation est rarement la finalit� d'une application, l'API log4j essaye d'�tre simple � comprendre et � utiliser. Loggers, Appenders and LayoutsJournaliseurs, Concateneurs et "Metteurs en forme"(n.d.t : vous trouverez � partir de ce point de plus en plus de termes en anglais (notamment les 3 pr�cedents) puisque se r�ferants directement � des classes de l'API log4j. La traduction du titre vous permet de comprendre de quoi il en retrourne) Log4j comporte trois composants principaux : loggers, appenders et layouts. Ces trois types de composants travaillent ensemble pour permettre aux d�veloppeurs de journaliser des notes en fonction d'un niveau et d'un type de note ainsi que de contr�ler lors de l'execution comment ces notes sont formatt�es et affich�es. Hi�rarchie des journaliseursL'interet principal d'une API de journalisation par rapport � un Les journaliseurs sont des entit�s nominatives. Les noms des journaliseurs sont sensibles � la casse des caract�res et suivent la r�gle de nommage hi�rarchique suivante :
Un journaliseur est dit anc�tre d'un autre
journaliseur si son nom suivi d'un point est un pr�fixe du
nom du journaliseur descendant. Un journaliseur est dit
parent d'un journaliseur fils si il y n'y a pas
d'anc�tres entre lui et le journaliseur descendant.
Par exemple, le journaliseur nomm� Le journaliseur "racine" est l'anc�tre de tous les journalisateurs. Il est unique en deux points :
L'invocation de la m�thode statique Logger.getRootLogger permet de le r�cuperer.
Tous les autres journaliseurs sont instanc�s et retrouv�s par la m�thode statique Logger.getLogger.
Cette m�thode prend comme param�tre le nom du journaliseur souhait�.
Quelques methodes basiques de la classe Logger sont list�es ci-apr�s.
Les journaliseurs peuvent �ventuellement avoir des niveaux donn�s.
Les diff�rents niveaux possibles, � savoir
DEBUG,
INFO,
WARN,
ERROR and
FATAL
sont d�finis dans la classe Si un journaliseur donn� n'a pas de niveau assign�, il h�rite alors de celui de l'anc�tre le plus proche ayant un niveau assign�.
De facon plus clair :
Le niveau h�rit� d'un journaliseur donn�e
C, est �gal au premier niveau non-null dans la hi�rarchie des journaliseurs, en commencant par C et en remontant dans la hi�rarchie jusqu'au journaliseur Pour �tre certain que tous les journaliseurs peuvent �ventuellement h�riter d'un niveau, le journaliseur racine a toujours un niveau d'assign�.
Vous trouverez ci-dessous diff�rents niveaux assign�s et le r�sultat des niveaux h�rit�s en se basant sur la r�gle pr�cit�e.
In example 1 above, only the root logger is assigned a
level. This level value,
In example 2, all loggers have an assigned level value. There
is no need for level inheritence.
In example 3, the loggers In example 4, the loggers Logging requests are made by invoking one of the printing methods
of a logger instance. These printing methods are
By definition, the printing method determines the level of a
logging request. For example, if A logging request is said to be enabled if its level is
higher than or equal to the level of its logger. Otherwise, the
request is said to be disabled. A logger without an
assigned level will inherit one from the hierarchy. This rule is
summarized below.
A log request of level p in a logger with
(either assigned or inherited, whichever is appropriate) level q, is enabled if p >=
q.
This rule is at the heart of log4j. It assumes that levels are
ordered. For the standard levels, we have Here is an example of this rule.
Calling the For example, in
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
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
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
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
the possible set of loggers. The developer is free to name the
loggers as desired.
Nevertheless, naming loggers after the class where they are
located seems to be the best strategy known so far.
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
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.
More than one appender can be attached to a logger.
The addAppender
method adds an appender to a given logger.
Each enabled logging
request for a given logger will be forwarded to all the appenders in
that logger as well as the appenders higher in the hierarchy. In
other words, appenders are inherited additively from the logger
hierarchy. For example, if a console appender is added to the root
logger, then all enabled logging requests will at least print on the
console. If in addition a file appender is added to a logger, say
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
the additivity flag to The rules governing appender additivity are summarized below.
The output of a log statement of logger C will
go to all the appenders in C and its ancestors. This is
the meaning of the term "appender additivity".
However, if an ancestor of logger C, say P,
has the additivity flag set to Loggers have their additivity flag set to
The table below shows an example:
More often than not, users wish to customize not only the output
destination but also the output format. This is accomplished by
associating a layout with an appender. The layout is
responsible for formatting the logging request according to the user's
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
format according to conversion patterns similar to the C language
For example, the PatternLayout with the conversion pattern "%r [%t]
%-5p %c - %m%n" will output something akin to:
The first field is the number of milliseconds elapsed since the
start of the program. The second field is the thread making the log
request. The third field is the level of the log statement. The
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 Object rendering follows the class hierarchy. For example, assuming
oranges are fruits, if you register an Object renderers have to implement the
ObjectRenderer
interface.
Inserting log requests into the application code requires a fair
amount of planning and effort. Observation shows that approximately 4
percent of code is dedicated to logging. Consequently, even moderately
sized applications will have thousands of logging statements embedded
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
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 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
to the pattern "%-4r [%t] %-5p %c %x - %m%n".
Note that by default, the root logger is assigned to
The output of MyApp is:
The figure below depicts the object diagram of
As a side note, let me mention that in log4j child loggers link
only to their existing ancestors. In particular, the logger named
The The previous example always outputs the same log information.
Fortunately, it is easy to modify This version of Here is a sample configuration file that results in exactly same
output as the previous Suppose we are no longer interested in seeing the output of any
component belonging to the The output of As the logger Here is another configuration file that uses multiple appenders.
Calling the enhanced MyApp with the this configuration file will
output the following on the console.
In addition, as the root logger has been allocated a second
appender, output will also be directed to the 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 The log4j library does not make any assumptions about its
environment. In particular, there are no default log4j
appenders. Under certain well-defined circumstances however, the
static inializer of the 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.
The exact default initialization algorithm is defined as follows:
See Loader.getResource(java.lang.String)
for the list of searched locations.
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.
The default log4j initialization is particularly useful in
web-server environments. Under Tomcat 3.x and 4.x, you should place
the You can also choose to set the system property
log4j.configuration before starting Tomcat. For Tomcat 3.x The
Example 1
The Unix shell command
Example 2
The Unix shell command
Example 3
The Windows shell command
Example 4
The Windows shell command
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, Initialization servlet
It is also possible to use a special servlet for log4j
initialization. Here is an example,
Define the following servlet in the web.xml file for your web-application.
Writing an initialization servlet is the most flexible way for
initializing log4j. There are no constraints on the code you can place
in the Most real-world systems have to deal with multiple clients
simultaneously. In a typical multithreaded implementation of such a
system, different threads will handle different clients. Logging is
especially well suited to trace and debug complex distributed
applications. A common approach to differentiate the logging output of
one client from another is to instantiate a new separate logger for
each client. This promotes the proliferation of loggers and
increases the management overhead of logging.
A lighter technique is to uniquely stamp each log request initiated
from the same client interaction. Neil Harrison described this method
in the book "Patterns for Logging Diagnostic Messages," in Pattern
Languages of Program Design 3, edited by R. Martin, D. Riehle,
and F. Buschmann (Addison-Wesley, 1997).
To uniquely stamp each request, the
user pushes contextual information into the NDC, the abbreviation of
Nested Diagnostic Context. The NDC class is shown below.
The NDC is managed per thread as a stack of contextual
information. Note that all methods of the To illustrate this point, let us take the example of a servlet
delivering content to numerous clients. The servlet can build the NDC
at the very beginning of the request before executing other code. The
contextual information can be the client's host name and other
information inherent to the request, typically information contained
in cookies. Hence, even if the servlet is serving multiple clients
simultaneously, the logs initiated by the same code, i.e. belonging to
the same logger, can still be distinguished because each client
request will have a different NDC stack. Contrast this with the
complexity of passing a freshly instantiated logger to all code
exercised during the client's request.
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
enhancement allows each virtual host to possess its own copy of the
logger hierarchy.
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
claims to be fast and flexible: speed first, flexibility second.
The user should be aware of the following performance issues.
When logging is turned
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 To avoid the parameter construction cost write:
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 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.
This is essentially the performance of walking the logger
hierarchy. When logging is turned on, log4j still needs to compare
the level of the log request with the level of the request
logger. However, loggers may not have an assigned
level; they can inherit them from the logger hierarchy. Thus,
before inheriting a level, the logger may need to search its
ancestors.
There has been a serious effort to make this hierarchy walk to
be as fast as possible. For example, child loggers link only to
their existing ancestors. In the The typical cost of walking the hierarchy is typically 3
times slower than when logging is turned off entirely.
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.
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
performance. Nevertheless, contributors frequently come up with new
optimizations. You should be pleased to know that when configured with
the SimpleLayout
performance tests have shown log4j to log as quickly as
Log4j is a popular logging package written in Java. 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
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
statements can remain in shipped code without incurring a heavy
performance cost.
|
--------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
