Log4j learning notes (reproduced)

xiaoxiao2021-03-06  46

To be honest, in addition to log4j's function, I prefer its logo. The following note is mainly "Borrow from" log4j's random document "Short Introduction to log4j", written by CEKI Gülcü in March 2002, other reference documents See it.

1, log4j has been ported to C, C , C #, Perl, Python, Ruby, Eiffel several languages. 2, log4j has three main components: recorder, storage device, layout 3, recorder (recorder can not care about log data storage) log4j allows programmers to define multiple recorders, each recorder has its own name By the name between the recorder, it indicates the affiliate relationship (or family relationship). Such as the recorder A.B, between the recording A.b.c is a parent child relationship, and the recorder A and A.b.c are the relationship between ancestors and future generations, and the father and child relationship is the special case of the ancestors and progeny. With this relationship, logical relationships between different recorders can be described. There is a recorder called the root recorder, which is always existed and cannot be retrieved or referenced by name, and it can be obtained through the logger.getrootlogger () method, and the general logger is passed through the Logger.getLogger method. Below is the basic method of the Logger class.

Package org.apache.log4j;

Public class logger {

// Creation & Retrieval Methods: Public Static Logger getRootLogger (); public static logger getlogger (String name);

// printing methods: 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);

// generic printing method: public void log (level L, Object Message);

The recorder has an important attribute, which is the level. (This is a good understanding, just like a family, there is a generation of generations, but the height of different members may not be the same, and the height and generations have nothing to do) programmers can give different recorders to different levels, if A member is not explicit, and the nearest level value is automatically inherited. The root recorder has a total level value. E.g:

Level value inherited by the recorder name Root Proot ProT x PX PX X.Y None PX x.y.z None PX

Programmers can freely define levels. There is a prejudice relationship between the level value, and there is a level value of each of the LOG information to be output, and there is a level value. In the previous logger class, several levels of Debug, Info, Warn, Error, Fatal are predefined. Because of the method binding, people are easy to misunderstand, in fact, these methods only indicate the log information to be recorded. level. When the log () method is called, the level of log information needs to be explicitly specified by parameters. If a log information is level, it is greater than the level value equal to the logger, then the logger will record it. If you feel difficult to understand, you can refer to the following example. // Get a logger instance named "com.foo" logger logger = 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 Barlogger = logger.getlogger ("com.foo.bar");

// this Request is enabled, Because Warn> = info. Logger.warn ("Low Fuel Level.");

// this Request is disabled, because debug

///// ' "" LOCATED NEAREST GAS Station. ");

// this request is disabled, Because Debug

There are a few interesting situations, one is when a recorder is instantiated, call getLogger () with the same name again, will return to it, which is very beneficial to use the same recorder in different code or classes LOG information, the other is that the ancestors in the nature are different from the descendants, and the ancestors of a recorder can appear late than the post-generation record, but will automatically establish such a family relationship according to the relationship between the name.

4. The storage device is output to the destination through the register. Supported registers include Console, Files, GUI Components, Remote Socket Servers, JMS, NT Event Loggers, Remote UNIX Syslog daemons. With the FILE storage, the log information can be output to a different file (ie, different destinations). LOG information can be stored asynchronously. A recorder can have multiple regulators that can increase the storage device by method addAppender. A blog information can be processed by this recorder, then the logger sent this information to the storage device that it it. Each recorder has a inheritance switch that determines whether the recorder is / not inherits the storage device of its parent logger. Note that if the inherit is only inherited, it is only inherited, regardless of the farther ancestor. Refer to the following table: Remarks of the recorder inherited by the recorder to store the destination Note Root A1 Not Applicable A1 The root logger is anonymous but can be asssed with the logger.getrootlogger () Method. There is no default appender attached to root X A-X1, A-X2 Appenders of "X" and root. XY None True A1, A-X1, A-X2 appenders of "x" and root. xyz A- XYZ1 TRUE A1, A-X1, A-X2, A-XYZ1 appenders in "xyz", "x" and root. security a-secret, since the additivity flag is set to false. security.access NONE TRUE A-Sec Only Appenders of "Security" Because The Additivity Flag in "Security" is set to false. 5, the layout layout is responsible for formatting the LOG information of the output. Log4j's PatternLayout can define formats with formatting templates similar to C language Printf. 6, log4j can automatically provide some log information according to the standards developed by the programmer, which is helpful to the case where the class that needs frequent logs. The object's automatic log has inheritance.

The front recorded some principles, today is a practice.

1. The study found that 4% of the code in a system is used to make Logging. 2, log4j's configuration file is used to set the level, regulator, and layout of the logger, which can pick up the setting of the set of key = value format or XML format. By configuration, you can create a log4J's operating environment. Log4J is running, do not do any assumptions for the environment, especially without the default storage. 3, there are several ways to configure log4j1) Call the BasicConfigurator.configure () method in the program; 2) Configure the file name by the command line parameter, parsing and configuring it through PropertyConfigurator.configure ; 3) Configure the file name and other information, by the environment variable, use the log4j default initialization process parsing and configured; 4) Configure the file name and other information, using the application server configuration, using a special servlets to complete the configuration. Look at the example: 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 what 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.doot (); logger.info ("exiting application.");}}

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!");}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} BasicConfigurator.configure Add a consolerapnder, output format It is set to "% -4R [% T]% -5p% C% X-% M% N" by patternLayout, and the default level of the root recorder is Level.debug.

The output is as follows: 0 [main] info myapp - Entering application.36 [main] debug com.foo.bar - DID IT AGAIN! 51 [main] info myapp - exiting application.

The following code combines configuration information, which will result in the same result as the above program. 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 protyconfigurator. PropertyConfigurator.configure (args [0]); Logger.info ("Entering Application)); bar bar = new bar (); bar.doot (); logger The contents of the configuration file are as follows: # set root logger level to debug and it.logger to a1.log4j.rootlogger = debug, A1 # a1 is set to be a consolerappender.log4j. appender.a1 = org.apache.log4j.consoleappender

# A1 uss patternLayout.log4j.Appender.a1.Layout = org.apache.log4j.patternLayoutLog4j.Appender.a1.Layout.conversionPattern =% - 4R [% T]% -5p% C% X-% M% N

With configuration files, you can easily modify the configuration. Log4j.Rootlogger = Debug, Stdout, R

Log4j.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.appender.stdout.Layout.conversionPattern =% 5P [% t] (% F:% L) -% M% N # print The date in ISO 8601 FormatLog4j. Appender.stdout.Layout.conversionPattern =% D [% T]% -5p% C -% M% N

Log4j.Appender.r = org.apache.log4j.rollingfileappenderlog4j.Appender.r.file = example.log

Log4j.Appender.r.maxfilesize = 100kb # Keep One Backup filelog4j.Appender.r.maxbackupindex = 1

Log4j.Appender.r.Layout = org.apache.log4j.patternLayoutLog4j.Appender.r.Layout.conversionPattern =% P% T% C -% M% N

# Print Only Messages of Level Warn OR Above In The package com.foo.log4j.logger.com.foo = WARN

For the tomcat4, using the transmission parameters of the environment variable, see the following example is provided unix export CATALINA_OPTS = "- Dlog4j.configuration = foobar.txt" <=== PropertyConfigurator resolved with export CATALINA_OPTS = "- Dlog4j.debug -Dlog4j.configuration = foobar.xml "<=== DOMConfigurator with windows are provided the following analytical set CATALINA_OPTS = -Dlog4j.configuration = foobar.lcf -Dlog4j.configuratorClass = com.foo.BarConfigurator <=== resolved by com.foo.BarConfigurator set CATALINA_OPTS = -Dlog4j.configuration = file: / c: /foobar.lcf configuration file location If it is not clear, put it in a web-inf / class directory. 4. Configuring the log4j below with the servlet is the article refer to the fire of Ice, and you have made some necessary modifications. It should be noted that the following code needs to write and publish it, there is no such class in JAR. I will write one later and put it up. I also wrote two, in the note (3). Added code in the web.xml file under the Application directory

log4jlog4j-init com.apache.jakarta.log4j.log4jinit log4j /web-inf/log4j.properties 1 this The paragraph code means that the com.apache.jakarta.log4j.log4jinit is loaded when Tomcat is started. This class file is called log4jinit.class. Wherein Log4jInit.class The source code package com.apache.jakarta.log4j; import org.apache.log4j.PropertyConfigurator; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http .HttpservletResponse; public class log4jinit extends httpservlet {

Public void init () {string prefix = getServletContext (). getRealPath ("/"); string file = getInitParameter ("log4j"); // if the log4j-init-file is not set, the no point in trying system. Out.println (".............. log4j start"); if (file! = null) {propertyconfigurator.configure (prefix file);}} public void doget (httpservletRequest Req, httpservletResponse res) {}} In the process of loading, the program reads /web-inf/log4j.properties this file. The configuration file is as follows: # set root logger level to debug and its Only appender to a1 # log4j has five levels of logger #fatal 0 # error 3 #warn 4 #info 6 #debug 7 # Configuring Root Logger, whose syntax is: # Log4j.rootlogger = [level], appendername, appendername, ... log4j.rootlogger = info, a1, r # This sentence is set to have all logs output # If log4j.rootlogger = Warn, it means that only Warn, Error, Fatal # is output, Debug, INFO will be blocked. # A1 is set to be a consolerappender. # Log4j Appender has several layers such as console, file, GUI components, and even sociable interface servers, NT event logger, UNIX Syslog daemon, etc. #ConsoleAppender output to the console log4j.Appender.a1 = ORG.Apache.log4j.consoleAppender # A1 used output layout, where log4j provides four layouts. Org.apache.log4j.htmlLayout (in HTML form form Layout) # org.apache.log4j.patternLayout (can be flexibly specified) Accurate time, thread, category, etc.

Log4j.Appender.a1.Layout = org.apache.log4j.patternLayout # flexible definition output format Specific View log4j javadoc org.apache.log4j.patternlayout #d time .... log4j.appender.a1.Layout.conversionPattern =% - D {YYYY-MM-DD HH: mm: SS} [% C] - [% P]% M% N #R Output to the file ROLLINGFILEAPPENDER extension, you can provide a backup function of a log. Log4j.Appender.r = org.apache.log4j.rollingfileaplender # log file name log4j.Appender.r.file = log4j.log # log file size log4j.Appender.r.maxFileSize = 100kb # Save a backup file log4j. Appender.r.maxbackupindex = 1log4j.appender.r.Layout = org.apache.log4j.tccLayout # log4j.Appender.r.Layout.conversionPattern =% - D {YYYY-MM-DD HH: mm: ss} [% C ] - [% P]% M% N

Configure root Logger, whose syntax is:

Log4j.rootlogger = [level], appendername, appendername, ...

Level is the priority of the log record, which is the specified log information output to which place. You can specify multiple output destinations at the same time.

Configure the log information output Destination Appender, its syntax is

Log4j.Appender.Appendername = full.qualified.name.of.Appender.classlog4j.Appender.Appendername.Option1 = value1 ... log4j.appender.Appendername.Option = VALUEN

Log4J provides the following: org.apache.log4j.consoleappender, org.apache.log4j.fileAppender (file), org.apache.log4j.dailyRollingFileAppender (a log file is generated every day), org.apache .log4j.rollingfileAppender (file size) When a new file is generated, org.apache.log4j.writerappender (send log information to any specified place in flow format)

Configure the format (layout) of log information, whose syntax is:

Log4j.Appender.Appendername.Layout = Fully.qualified.Name.Of.Layout.ClassLog4j.Appender.Appendername.Layout.Option1 = value1 .... log4j.appender.Appendername.Layout.Option = VALUEN

Layout provided by log4j: org.apache.log4j.htmlLayout (layout in HTML form), org.apache.log4j.patternlayout (can be flexibly specified), org.apache.log4j.simplelayout (including log Level and information string of information), org.apache.log4j.ttcccLayout (including time, thread, category, etc.) I have two programs, one is a normal Java program that implements a "ninety-nine" Table "; the other is a servlet. The Tomcat I used here is 4.1.12, J2se is 1.3.1, the Log4j version is 1.2.8.

First, nine nine tables. Environment settings: Need to put log4j-1.2.8.jar into the ClassPath variable. The content of the Hello.java file is as follows:

Import org.apache.log4j. *; public class hello {static logger logger = logger.getlogger (hello.class); public static void main (string [] args) {Int i, j; // Basicconfigurator.configure (); PropertyConfigurator.configure (args [0]); logger.info ("Entering Application."); For (i = 1; i <10; i ) {logger.debug (" i); for (j = 1; J <= i; j ) {logger.warn ("" j); system.out.print (i * j); system.out.print ("/ t");} system.out.println ("" " ("Exiting application.");} Log4j's profile log4j.inf is as follows: log4j.rootlogger = WARN, Stdout, rlog4j.appender.stdout = org.apache.log4j.consoleAppenderlog4j.Appender. STDOUT.LAYOUG4J.PATTERNLAYOUT # pattern to output the caller's file name and line number. # log4j.connder.stdout.Layout.conversionPattern =% 5P [% T] (% F:% L) -% M % N # Print The Date in IN IN IN IN IN INSO 8601 FORMATLOG4J.APPENDER.STDOUT.LAYOUT.CONVERSIONPATTERN =% D [% T]% -5p% C -% M% NLog4j.log4j.r = org.apache.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 # Print Only Messages of Level Warn OR Above in the package com.foo.log4j.logger.com.foo = WARN Run: javac hello.javajava hello log4j.inf results will display on the screen, And record in the example.log file.

Second, servlet environment settings: Place log4j-1.2.8.jar and servlet.jar into environment variables ClassPath and to copy log4j-1.2.8 to $ Tomcat_home / common / lib directory. Assume that there is a deployment to Tomcat app called myWeb. The content of the servlet program log4jinit.java is in $ TOMCAT_HOME / WebApps / MyWeb / Web-INF / CLASS / COM / HEDONG / LEARNING / LOG4J / Directory, the content is as follows: package com.hedong.Learning.log4j; import org.apache.log4j . *; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Log4jInit extends HttpServlet {public void init () {String prefix = getServletContext () getRealPath. ("/"); String file = GetinitParameter ("log4j"); // if The log4j-init-file is not set, the no point in trying system.out.println ("......... ....... log4j start "); if (file! = null) {propertyconfigurator.configure (prefix file);}} public void doget (httpservletRequest Req, httpservletResponse res) {}} in log4jinit.java Compile it: Javac log4jinit.javamyweb set file Web.xml In the $ TOMCAT_HOME / WebApps / MyWeb / Web-INF / directory, the following red part is added.

......... log4j-init com.hedong.learning.log4j.log4jinit log4j Web-inf / log4j.properties 1 At the same time, build a file name called log4j.properties in this directory, as follows: log4j.rootlogger = info, a1, rlog4j.appender .A1 = org.apache.log4j.consoleappender log4j.Appender.a1.Layout = org.apache.log4j.patternLayout log4j.Appender.a1.Layout.conversionPattern =% - D {yyyy-mm-dd hh: mm: ss} [% C] - [% P]% m% n log4j.Appender.r = org.apache.log4j.rollingfileAppenderlog4j.Appender.r.file = $ TOMCAT_HOME / WebApps / dbweb / logs / log4j.log <---- the $ TOMCAT_HOME into the installation directory of tomcat log4j.appender.R.MaxFileSize = 100KBlog4j.appender.R.MaxBackupIndex = 1log4j.appender.R.layout = org.apache.log4j.PatternLayoutlog4j.appender.R.layout.ConversionPattern =% P% T% C -% M% N remember, don't forget to create a directory $ tomcat_home / webApps / dbweb / logs / if it does not exist. Create a directory $ TOMCAT_HOME / WebApps / DBWeb / Test /, then create a file Test.jsp in this directory, the content is as follows: <% @ Page ContentType = "text / html; charset = GB2312"%> <% @ Page Import = "org.apache.log4j. *"%> <% logger logger = logger.getlogger ("test.jsp"); logger.info ("befor Say Hi");%>

hi <% Logger.info ("After Say Hi");%> then restart Tomcat, access this JSP page via browser, such as http://yourdomain.com:8080/Myweb/test/test.jsp, if everything is normal, Will see a big hi.

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

New Post(0)