4. Configuration
Inserting log requests into the application code requires a lot of pre-planning and final efforts. It is shown that about 4% of the code is used for output.
Therefore, programs of moderate size are embedded with thousands of log output statements. To manage the output status of these logs in a way that does not require manual management, it is imperative to number and standardize the log output.
Log4j is fully configurable in the program. However, using the configuration file to configure log4j is more flexible. Currently, its configuration file supports two formats: XML and Java properties (Key = value.
Let's use an example to demonstrate how it works. Suppose there is a program MyApp that uses log4j.
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
// Logger instance named "MyApp ".
Static logger = logger. getlogger (MyApp. Class );
Public static void main (string [] ARGs ){
// Set up a simple configuration that logs on the console.
Basicconfigurator. Configure ();
Logger.info ("entering application .");
Bar = new bar ();
Bar. doit ();
Logger.info ("exiting application .");
}
}
MyApp starts with introducing the related classes of log4j. Then it defines a static logger variable and gives the full path name with the value "MyApp.
MyApp uses the bar class defined in the package com. Foo.
Package com. Foo;
Import org. Apache. log4j. Logger;
Public class bar {
Static logger = logger. getlogger (bar. Class );
Public void doit (){
Logger. debug ("did it again! ");
}
}
The basicconfigurator. Configure () method is called to create a fairly simple log4j setting. It is added to 1
Consoleappender to the root logger. The output is in the "%-4r [% T] %-5 p % C % x-% m % N" mode.
.
Note that the root logger is assigned the level of level. debug by default.
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.
The following figure describes the object map of MyApp after the basicconfigurator. Configure () method is called.
One thing to note is that the log4j sub-logger only connects to the existing parent database. Specifically
The Logger of COM. Foo. Bar is directly connected to the root logger, instead of the useless com or com. foo
Logger. This significantly improves program performance and reduces memory usage.
The MyApp class configures log4j by calling the basicconfigurator. Configure method. Other classes only
You need to introduce the org. Apache. log4j. Logger class, find the logger they want to use, and use it.
In the previous example, the same log information is usually output. Fortunately, it is easy to modify MyApp so that logs can be lost.
Output can be controlled at runtime. Here is a slightly modified version.
Import com. Foo. bar;
Import org. Apache. log4j. Logger;
Import org. Apache. log4j. propertyconfigurator;
Public class MyApp {
Static logger = logger. getlogger (MyApp. Class. getname ());
Public static void main (string [] ARGs ){
// Basicconfigurator replaced with propertyconfigurator.
Propertyconfigurator. Configure (ARGs [0]);
Logger.info ("entering application .");
Bar = new bar ();
Bar. doit ();
Logger.info ("exiting application .");
}
}
The modified MyApp notification program calls the propertyconfigurator () method to parse a configuration file and
Configure logs according to the configuration file.
Here is an example of a configuration file, which will generate the same as the basic example of basicconfigurator.
.
# Set root logger level to debug and its only appender to A1.
Log4j. rootlogger = debug, A1
# A1 is set to be a consoleappender.
Log4j. appender. A1 = org. Apache. log4j. leleappender
# A1 uses patternlayout.
Log4j. appender. a1.layout = org. Apache. log4j. patternlayout
Log4j. appender. a1.layout. conversionpattern = %-4r [% T] %-5 p % C % x-% m % N
If we are not interested in the output of any class in the com. Foo package, the subsequent configuration file will show us
Is one of the methods to achieve this goal.
Log4j. rootlogger = debug, A1
Log4j. appender. A1 = org. Apache. log4j. leleappender
Log4j. appender. a1.layout = org. Apache. log4j. patternlayout
# Print the date in iso8601 format
Log4j. appender. a1.layout. conversionpattern = % d [% T] %-5 p % C-% m % N
# Print only messages of level warn or abve in the package com. Foo.
Log4j.logger.com. Foo = warn
The MyApp configured in this configuration file will output the following:
2000-09-07 14:07:41, 508 [main] info MyApp-entering application.
2000-09-07 14:07:41, 529 [main] info MyApp-exiting application.
When logger com. Foo. bar is not assigned a level, it will inherit from Com. Foo, in the configuration file
It is set to the warn level. The log defined in the bar. doit method is debug level, lower than warn,
Therefore, log requests of the doit () method are disabled.
Here is another configuration file, which uses multiple appenders.
Log4j. rootlogger = debug, stdout, R
Log4j. appender. stdout = org. Apache. log4j. leleappender
Log4j. appender. stdout. layout = org. Apache. log4j. patternlayout
# Pattern to output the caller's file name and line number.
Log4j. appender. stdout. layout. conversionpattern = % 5 p [% T] (% F: % L)-% m % N
Log4j. appender. r = org. Apache. log4j. rollingfileappender
Log4j. appender. R. File = example. Log
Log4j. appender. R. maxfilesize = 100kb
# Keep one backup file
Log4j. appender. R. maxbackupindex = 1
Log4j. appender. R. layout = org. Apache. log4j. patternlayout
Log4j. appender. R. layout. conversionpattern = % P % T % C-% m % N
The MyApp class strengthened by calling this configuration file will output the following information.
Info [main] (myapp2.java: 12)-entering application.
Debug [main] (bar. Java: 8)-doing it again!
Info [main] (myapp2.java: 15)-exiting application.
In addition, because the root logger has been assigned a second appender, the output will also be directed to the example. log file.
When the file size reaches kb, it will be automatically backed up. The example. log file of the old version is automatically moved to the backup
File example. log.1.
Note that we can obtain these different log behaviors without re-compiling the code. We can easily
Logs are output to Unix Syslog daemon, redirecting all com. Foo to NT Event logger,
You can also forward logs to a remote log4j server, which outputs logs according to the policies of the local server. Example
For example, forward a log event to the second log4j server.
5. Default initialization process
The log4j class library does not make any assumptions about its environment. In particular, there is no default log4j appender. In some special
In a well-defined environment, logger's static inializer will attempt to automatically configure log4j.
The features of the Java language ensure that the static initializer of the class is called only once when the class is loaded to the memory.
One important thing to remember is that different class loaders may load completely different copies of the same class.
These copies of the same type are considered completely irrelevant by virtual machines.
The default Initialization is very useful, especially when the runtime environment on which some applications depend is accurate.
Location. For example, the same application can be used as a standard application or
Applet, or a servlet under the control of web-server.
The correct default initialization principle is defined as follows:
1. Set the system attribute log4j. defaultinitoverride to a value other than "false", then log4j will
Skip the default initialization process.
2. Set the resource variable string to the system attribute log4j. configuration. Define the default Initialization
The best way to file is through the system attribute log4j. configuration. In case of System Properties
Log4j. configuration is not defined, so set the default value for the string variable resource.
Log4j. properties.
3. Try to convert the resource variable to a URL.
4. If the value of the variable resource cannot be converted into a URL, for example, because of malformedurlexception violation
For example
Org. Apache. log4j. helpers. loader. getresource (resource, logger. Class) method from
Search for resource in classpath. It returns a URL and notifies log4j. properties that the value is an error.
Invalid URL.
See loader. getresource (Java. Lang. String) to view the list of search locations.
5. If no URL is found, discard the default initialization. Otherwise, use the URL to configure log4j.
Propertyconfigurator will be used to parse the URL and configure log4j, unless the URL ends with ". xml.
In this case, the domaggregator will be called. You can have the opportunity to define a custom
Aggregator.
The system attribute log4j. configuratorclass value is taken from the full path of your custom class name.
Your custom aggregator must implement the aggregator interface.
6. Configuration example
6.1 Tomcat Initialization
The default log4j initialization typical application is in the Web-server environment. In tomcat3.x and tomcat4.x
You should put the configuration file log4j. properties in the WEB-INF/classes directory of your Web Application
.
Log4j discovers attribute files and initializes them accordingly. This is the easiest way to make it work.
You can also set the system attribute log4j. configuration before running tomcat. For Tomcat 3.x,
Tomcat_opts system variables are used to set command line options. For tomcat4.0, the system environment is changed
Catalina_opts replaces tomcat_opts.
Example 1
Unix Command Line
Export tomcat_opts = "-dlog4j.configuration=foobar.txt"
Log4juses the foobar.txt file as the default configuration file. This file should be placed in WEB-INF/classes
Directory. This file will be read by propertyconfigurator. Each web-application uses a different default
Configuration file, because each file is related to its Web-application.
Example 2
Unix Command Line
Export tomcat_opts = "-dlog4j. debug-dlog4j. Configuration = foobar. xml"
Tells log4j to output debugging information for the Log4j-internal and uses foobar. XML as the default configuration file.
This file should be placed in the WEB-INF/classes directory of your web-application. Because of. xml
It will be read by the domaggregator. Each web-application uses a different default
Configuration file. Because each file is related to its Web-application.
Example 3
Unix Command Line
Set tomcat_opts =-dlog4j. Configuration = foobar. LCF-dlog4j. configuratorclass = com. Foo. barconfigurator
Tell log4j to use the file foobar. LCF as the default configuration file. This file should be stored in your
The WEB-INF/classes directory for web-application. Because the log4j. configuratorclass system is defined
The file will be parsed using the custom com. Foo. barconfigurator class. No
The same as the default configuration file. Because each file is related to its Web-application.
Example 4
Unix Command Line
Set tomcat_opts =-dlog4j. Configuration = file:/C:/foobar. LCF
Tell log4j to use the file foobar. LCF as the default configuration file. This configuration file uses URL File:/C:/foobar. LCF
The full path name is defined. In this way, the same configuration file will be used by all web-applications.
Different web-applications use their own class loaders to load log4j. In this way
Environment will operate independently without any mutual synchronization. For example, multiple web-Applications define
Fileappenders of the same output source will try to write the same file. The result seems to be a lack of security.
Make sure that the same system resources are not used in the log4j configuration of each different web-application.
6.2 servlet Initialization
It is also possible to use a special servlet for log4j initialization. The following 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 subsequent servlet in Web. XML for your web-application.
Log4j-init
Com. Foo. log4jinit
Log4j-init-file WEB-INF/classes/log4j. LCF
1
Writing an initialized servlet is the most flexible method for initializing log4j. There are no restrictions in the code. You can
To define it in the servlet init method.