Log4j Concise Manual (23)

zhaozj2021-02-16  85

4. Configure the Insert log request to the application's code requires a large number of pre-planning and final efforts. Observation shows that about 4% of the code is used to output. Therefore, the size of the size mode is embedded with thousands of log output statements. In order to manage the output status of these logs in a manual manner, it is imperative to output to the log output to numbered and specification. Log4j has sufficient configurability in the program. However, configuring log4j with a configuration file with greater flexibility. Currently, its profile supports both formats of XML and Java Properties files. Let us demonstrate how it is doing in an example. Assume that there is a program myApp with 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 the // Logger instance named "MyApp" .static Logger 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 bar = new bar (); bar.doit (); logger.info ("exiting application.");}} myApp To introduce the relevant class of log4j, then it is defined A static logger variable and gives a full path name for the "MyApp" class. MyApp uses class bar.package com.foo; import org.apache.log4j.logger; public class bar {static logger logger = logger.getlogger (bar.class); public void doit () {Logger.debug ("DID IT Again!");}} Call the BasicConfigurator.configure () method creates a fairly simple Log4j setting. It adds a consolerapnder to the root Logger. The output will be formatted by PatternLayout in "% -4R [% T]% -5p% C% X-% M% N" mode. Note that the root Logger is assigned the level of Level.Debug by default. MyApp's output is: 0 [main] info myapp - Entering Application.36 [main] debug com.foo.bar - DID IT Again! 51 [main] info myapp - exiting application. Subsequent graphic description is called BasicConfigurator.configure () Method of MYAPP after the method. While wanting to remind, Log4j's child logger is only connected to their parents already existing. In particular, logger named com.foo.bar is directly connected to the root Logger instead of the useless COM or com.foologigger. This significantly improves program performance and reduces memory occupation. MyApp class configuration log4j is by calling the BasicConfigurator.configure method.

Other classes only need to introduce org.apache.log4j.logger classes, find the Logger they want to use, and use it to play. Previous examples typically output the same log information. Fortunately, modify myApp is easy, so that log output can be controlled at runtime. Here is a small modified version. 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 ()); public static void main (String [] args) {// BasicConfigurator replaced with propertyconfigurator.propertyconfigurator.configure (args [0]); Logger.info ("Entering Application)); bar bar bar = new bar (); bar.doit (); logger .info ("exiting application.");}} The modified MyApp Notification Program calls the PropertyConfigurator () method to resolve a configuration file and set the log according to this profile. Here is an example of a configuration file, which will produce the same output result 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.ConsoleAppender # A1 uses PatternLayout.Log4j. appender.a1.Layout = org.apache.log4j.patternlayoutlog4j.appender.a1.Layout.conversionPattern =% - 4R [% T]% -5p% C% x -% M% N assumes that we are not in the com.foo package If any class is interested, the subsequent profile shows us one of the methods that implement this purpose. Log4j.rootLogger = DEBUG, A1Log4j.appender.A1 = org.apache.Log4j.ConsoleAppenderLog4j.appender.A1.layout = org.apache.Log4j.PatternLayout # Print the date in ISO 8601 formatLog4j.appender.A1.layout.ConversionPattern = % D [% T]% -5p% C -% M% N # print ONLY Messages of Level Warn or Above in the package com.foo.log4j.logger.com.foo = WARN is configured with this configuration file MYAPP The output is as follows: 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 Assign a level, it will inherit from com.foo, which is set in the configuration file.

Log defined in bar.doit method is a debug level, lower than WARN, so the log request for the DOIT () method is disabled. Here is another configuration file, which uses a plurality of appenders.Log4j.rootLogger = debug, stdout, RLog4j.appender.stdout = org.apache.Log4j.ConsoleAppenderLog4j.appender.stdout.layout = org.apache.Log4j.PatternLayout # Pattern to output the caller's file name and line number.log4j.connder.stdout.Layout.conversionPattern =% 5P [% t] (% F:% L) -% m% nlog4j.log4j. RollingFileAppenderLog4j.appender.R.File example.logLog4j.appender.R.MaxFileSize = 100KB # Keep one backup fileLog4j.appender.R.MaxBackupIndex = 1Log4j.appender.R.layout = org.apache.Log4j.PatternLayoutLog4j.appender.R = .Layout.conversionPattern =% P% T% C -% M% N N with this profile called the MyApp class 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, the output will also be oriented to Example.log because the root Logger is assigned a second apnder. file. This file is automatically backed up when the file size is 100KB. When backed up, the old version of the eXample.log file is automatically moved to file eXample.log.1. Note We don't need to recompile the code to get these different log behaviors. We can easily enable the log to output to UNIX Syslog Daemon, redirect all COM.FOO to NT Event Logger, or forward the log to a remote Log4J server, which is logged according to the local Server policy. For example, forward log events to the second log4j server. 5. The default initialization process log4J class library does not make any assumptions to its environment. Especially there is no default log4j appender. In some particularly a well-defined environment, Logger's static inIalizer will try to automatically configure log4j. The Java language features ensure that only the static initializer of the class is only called once when it is loaded to memory. It is important to remember that different types of loaders may load a completely different copy of the same class. These same copies are considered completely unsatisfactory by virtual machines. The default initialization is very useful, especially in the case where the operating environment relied on some applications is accurately positioned. For example, the same application can be used as a standard application, or an applet, or a servlet under Web-Server. Accurate default initialization principle is defined as follows: 1. Set the system properties log4j.defaultinitoverride is other than other values ​​other than "false", then log4j will skip the default Initialization process. 2. Set the resource variable string to the system properties log4j.configuration. The best way to define the default initialization file is through system properties log4j.configuration.

In the event of a system property log4j.configuration is not defined, then set the string variable resource to its default value log4j.properties. 3. Try to convert the resource variable as a URL. 4. If the value of the variable resource cannot be converted to a URL, for example due to the Malformedurlexception violation, then search for Resource from the classpath by calling org.apache.log4j.helpers.Loader.GetResource (resource, logger.class) method, it will return A URL and notify "log4j.properties" value is an error URL. Look at see loader.getResource (java.lang.string) View the list of search locations. 5. If there is no URL being discovered, then give up the default Initialization. Otherwise, use the URL to configure log4j. PropertyConfigurator will be used to parse the URL, configure log4j, unless the URL ends with ".xml". In this case DOMCONFIGURAM will be called. You can have a chance to define a custom Configurator. System Properties Log4j.configuratorclass's value takes the full path to your custom class name. Your custom Configurator must implement the Configurator interface. 6. Configuration Example 6.1 Initialization Default Log4j INITISATION Typical Log4j INITIALIZATION is typically in a web-server environment. Under Tomcat3.x and Tomcat4.x, you should put the configuration file log4j.properties in your web-INF / CLASSES directory of your Web application. Log4j will discover attribute files and initialized this. This is the easiest way to make it work. You can also choose to set the system properties log4j.configuration before running Tomcat. For Tomcat 3.x, Tomcat_OPTS system variable is an option to set the command line. For Tomcat 4.0, use the system environment variable Catalina_OPTS instead of Tomcat_OPTS. Example 1 UNIX command line Export Tomcat_opts = "- DLOG4J.CONFIGURATION = FOOBAR.TXT" tells the log4j to use the file foobar.txt as the default configuration file. This file should be placed in a web-inf / class directory. This file will be read by PropertyConfigurator. Each Web-Application will use different default configuration files because each file is related to its web-application. Example 2 UNIX command line Export Tomcat_opts = "- DLOG4J.DEBUG4J.CONFIG4J.DEBUG4J.CONFIGURATION = FOOBAR.XML" tells the log4j to output log4j-internal debugging information, and use FOOBAR.XML as the default configuration file. This file should be placed in your web-application's web-inf / class directory. Because there is a .xml extension, it will be read by Domconfigurator. Each Web-Application will use different default configuration files. Because each file is related to its web-applation. Example 3 UNIX command line set tomcat_opts = -dlog4j.configuration = foobar.lcf -dlog4j.configuratorclass = com.foo.barconfigurator tells the log4j to use file foobar.lcf as the default configuration file. This file should be placed in your web-application's web-inf / class directory.

Because the log4j.configuratorclass system properties are defined, the file will be parsed by a custom COM.FOO.BARCONFIGURATOR class. Each Web-Application will use different default configuration files. Because each file is related to its web-applation. Example 4 UNIX command line set tomcat_opts = -dlog4j.configuration = file: / c: /foobar.lcf tells the log4j to use the file foobar.lcf as the default configuration file. This configuration file defines a full path name with URL File: / C: /foobar.lcf. The same configuration file will be used by all Web-Application. Different Web-Application will load LOG4J through their own type loaders. In this way, each Log4J environment will operate independently without any mutual synchronization. For example: FileAppenders that exactly the same output source will try to write the same file in multiple web-applications. The result is like lack of security. You must ensure that the Log4j configuration of each different web-application is not used to use the same system resource. 6.2 The initialization of servlet uses a special servlet to do the 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 tryingif (file = null!) {PropertyConfigurator.configure (prefix file);}} public void doGet (HttpServletRequest req, HttpServletResponse res) {}} in Define subsequent servlets 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 elastic initialization Log4j method. There is no restriction in the code, you can define it in the servlet's init method.

转载请注明原文地址:https://www.9cbs.com/read-12773.html

New Post(0)