log4j-1.2.9. Configuration under tomcat5.5 (EXT)

Source: Internet
Author: User
Tags html form print format tomcat log4j
Key Words: Log copy Log4j-1.2.9.jar to/web-inf/lib directory
It's no use adding Log4j-1.2.9.jar references in Eclipse's Java builder path

Under the copy Log4j-1.2.9.jar to/web-inf/lib

TomcatYou need to automatically find the lib below this directory at startup, and the Eclipse reference is used in development use and, in the absence of a release, TomcatThese classes are not found

Jian commons- logging.propertiesFile
Build commons-in/web-inf/classes directory logging.propertiesFile

Content is

Org.apache.commons.logging.log=org.apache.commons.logging.impl.log4jlogger



Build log4j.properties File
The contents are as follows in the/web-inf/classes directory to build log4j.properties files



Log4j.rootlogger=info,logfile,stdout

#上面的INFO表示 LogThe level of output is info



Log4j.appender.stdout=org.apache.log4j.consoleappender

Log4j.appender.stdout.layout=org.apache.log4j.patternlayout

log4j.appender.stdout.layout.conversionpattern=%d%p [%c]-<%m>%n



Log4j.appender.logfile=org.apache.log4j.rollingfileappender

Log4j.appender.logfile.file=c:/eclipse/workspace/recommend/log/operation.log

log4j.appender.logfile.maxfilesize=512kb

# Keep three backup files.

Log4j.appender.logfile.maxbackupindex=0

# Output:date Priority [Category]-message

Log4j.appender.logfile.layout=org.apache.log4j.patternlayout

log4j.appender.logfile.layout.conversionpattern=%d%p [%c]-%m%n



# If programmed properly the most messages would is at DEBUG

# and the least at FATAL.



The use of log4j/log4e
Log4j is to help developers LogThe API class library for output management. Its most important feature is the flexibility to configure the file settings LogPriority of information, LogThe output destination of the information and LogThe output format of the information.

log4j in addition to recording program running LogAnother important feature of information is that it is used to display debugging information.

Programmers often encounter situations that break out of the Java IDE Environment debugger, when most people choose to use System.out

The. println statement outputs a variable value method for debugging. This poses a very troubling question: once where daysThe programmer decided not to display the System.out.println, but to comment out the spam statements on a line. If where daysIf you want to debug variable values, you can only remove these comments in a row to recover the SYSTEM.OUT.PRINTLN statement.

Using log4j can be a good treatment for similar situations. Log4j use method The following is a log4j of some theoretical knowledge

To define a configuration file
Using a configuration file first will make our applications more flexible in configuring log LogOutput mode includes output priority, output destination, output format. LOG4J supports two configuration file formats, one in XML format and one for Java attribute file Log4j.properties (key = value).

The following describes how to use the Log4j.properties file as a configuration file:

Configure Root Logger
Its syntax is: Log4j.rootlogger = [level], Appendername, Appendername, ...

L Output Priority level

[Level] is LogThe priority of the record, which is divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or custom levels.

LOG4J recommends using only four levels, from high to low, respectively, for error, WARN, INFO, and DEBUG.

By the level defined here, you can control the corresponding level in the application LogInformation on the switch. For example, where the info level is defined, all debug levels in the application LogInformation will not be printed.

L Output Destination

Output format configuration for specific output
L Output-type configuration

Appendername is the designation LogWhere the information is being exported. Multiple output destinations can be specified at the same time.

Configuration LogThe information output destination is Appender, and its syntax is:

Log4j.appender.appenderName = Fully.qualified.name.of.appender.class

Log4j.appender.appenderName.option1 = value1 ...

Log4j.appender.appenderName.option N = Valuen

Among them, LOG4J provides the following appender:

Org.apache.log4j.ConsoleAppender (console),

Org.apache.log4j.FileAppender (file),

Org.apache.log4j.DailyRollingFileAppender ( every daysProduce a LogFile),

Org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches the specified size),

Org.apache.log4j.WriterAppender (Will LogInformation is sent in streaming format to any specified place)

L Configuration LogFormat of information (layout)

Its syntax is:

Log4j.appender.appenderName.layout = Fully.qualified.name.of.layout.class

Log4j.appender.appenderName.layout.option1 = value1 ...

Log4j.appender.appenderName.layout.option = Valuen

Among them, LOG4J provides the following layout:

Org.apache.log4j.HTMLLayout (layout in HTML form),

Org.apache.log4j.PatternLayout (You can specify layout patterns flexibly),

Org.apache.log4j.SimpleLayout (contains LogThe level of information and the information string),

Org.apache.log4j.TTCCLayout (contains LogGenerated time, thread, category, etc. information)

log4j format with print format similar to the printf function in C language LogInformation

The printing parameters are as follows:

%M the message specified in the output code

%p output priority, i.e. Debug,info,warn,error,fatal

%r output the number of milliseconds it takes to boot to output the log information

The class to which the%c output belongs, usually the full name of the class in which it is located

%t output produces the LogThe thread name of the event

%n output a carriage return line break, the Windows platform is "/r/n", and the UNIX platform is "/n"

%d output LogThe date or time of the point, the default format is ISO8601, or you can then

Specify the format, such as:%d{yyy MMM DD Hh:mm:ss,sss},

Output similar to: October 18, 2002 22:10:28,921

%l output LogWhere the event occurred, including the class name, the thread that occurred, and the number of lines in the code.

Example: Testlog4.main (testlog4.java:10)





Using log4j in your code
L Get LogRecorder

Using log4j, the first step is to get LogRecorder, this recorder will be responsible for controlling LogInformation.

Its syntax is:

public static Logger GetLogger (String name)

Gets the logger by the specified name and, if necessary, creates a new logger for that name. Name generally takes the names of this class, such as:

static Logger Logger = Logger.getlogger (ServerWithLog4j.class.getName ())

L Read configuration file

When you get the LogAfter the logger, the second step configures the log4j environment,

The syntax is: basicconfigurator.configure (): Automatically and quickly uses the default log4j environment.

Propertyconfigurator.configure (String configfilename):

Read the configuration file written using the Java feature file.

Example: Propertyconfigurator.configure (".//src//log4j.properties")

Domconfigurator.configure (String filename): Reads a configuration file in XML form.

L Insert record information (format LogInformation

When the two necessary steps are completed, you can easily use different priority levels LogThe record statement is inserted where you want to record LogAnywhere, its syntax is as follows:

Logger.debug (Object message);

Logger.info (Object message);

Logger.warn (Object message);

Logger.error (Object message);

LOG4J Sample Program
The following is a simple example program to further illustrate how log4j is used.

The program code is as follows:

Import org.apache.log4j.*;

public class Logtest {

static Logger Logger = Logger.getlogger (LogTest.class.getName ());

public static void Main (string[] args)

{

Propertyconfigurator.configure (".//src/log4j.properties");

Ogger.debug ("Debug ...");

Logger.info ("info ...");

Logger.warn ("Warn ...");

Logger.error ("error ...");

}

}

Program Description:

①static Logger Logger = Logger.getlogger (LogTest.class.getName ());

is to create a logger object that belongs to the Logtest class and tell logger what your current class is when you create it.

②propertyconfigurator.configure ("Log4j.properties")

This means using the log4j.properties file in the SRC folder under the current engineering directory as the configuration file.

If you put the log4j.properties in the engineering root directory or do not write this sentence, the program will automatically find the configuration file.

③logger.debug is the information that outputs debug,

Logger.info is the output hint information,

Logger.warn is to display a warning message,

Logger.error is to display an error message.

The following are the contents of the configuration file log4j.properties: Log4j.rootlogger

Log4j. Rootlogger =debug, Stdout,r

Log4j.appender.stdout=org.apache.log4j.consoleappender

Log4j.appender.stdout.layout=org.apache.log4j.patternlayout

log4j.appender.stdout.layout.conversionpattern=%5p (%f:%l)-%m%n

Log4j.appender.r=org.apache.log4j.rollingfileappender

Log4j.appender.r.file=log.txt log4j.appender.r.maxfilesize=100kb

Log4j.appender.r.maxbackupindex=1

Log4j.appender.r.layout=org.apache.log4j.patternlayout

LOG4J.APPENDER.R.LAYOUT.CONVERSIONPATTERN=%D{YYYY MMM DD HH:mm:ss}%-5p%c-%m%n



Program Description:
L log4j. Rootlogger =debug, Stdout,r

That means I'm going to show all the priority equal to and above debug information. "stdout", "R" means that I have defined two outputs (whatever name is good). The following three lines say that the stdout output is actually the standard output console, which is the screen.

L The output format is patternlayout. The conversion mode is%5p (%f:%l)-%m%n,

The first five are used to display precedence, and then the current file name, plus the current number of rows, is displayed.

Finally, the information in Logger.debug () or logger.info () or Logger.warn () or Logger.error ().

%n indicates a carriage return blank line.

Plus the following six lines log information is not only displayed on the screen, but will be saved in a file called "Log.txt" with a maximum file of 100KB. If the file size exceeds 100KB, the file is backed up as "Log.txt.1", and the new "Log.txt" continues to log the log information. Next we can change the log4j.properties, without recompiling, we can control whether the log information is displayed, the output type of the log information, the output mode, the output format, and so on.

Examples are as follows:
Put "log4j" in the Log4j.properties file. Rootlogger =debug,stdout,r "

Rewrite it as "Log4j.rootcategory=off, stdout,r" so that all log information is not displayed;

Put "log4j" in the Log4j.properties file. Rootlogger =debug,stdout,r "Rewrite to" Log4j.rootcategory=info, stdout,r, so that only the log information of info, WARN and error is displayed, and DEBUG information is not displayed; Using log4j in Web programs attention issues

1, because the JSP or servlet in the execution state does not have the current path concept, all use

Propertyconfigurator.configure (String) statement when looking for a log4j.properties file, give the corresponding

The path to the current JSP or servlet translates into an absolute file system path.

method is to use the Servletcontext.getrealpath (string) statement.

Example://Get current jsp path String prefix = Getservletcontext (). Getrealpath ("/");

Read

Log4j.properties propertyconfigurator.configure (prefix+ "//web-inf//log4j.properties");



2, the corresponding Log4j.properties set a property when you want to set the absolute path in the program.

Example: Log4j.appender.r.file property setting LogThe location where the file is stored.

We can make flexible settings using the method of reading and writing. Properties configuration file.

log4e use instructions after understanding the features of the log4j

We will certainly write some log4j in our program LogRecording.

For programmers who use Eclipse, log4e will be our most effective log4j LogWriting Assistant, now start log4e trip. LOG4E is a free eclipse Plugin that helps you quickly add log to your Java project, and we can download the latest version of log4e on Http://log4e.jayefem.de/index.php/Download Web site.

After downloading, copy the appropriate folder to eclipse's plug-in directory, and then eclipse, with one more log4e option in the preferences. LOG4E can have multiple insert log as a method, class, and, of course, you can insert the log at the current location.

At the same time, it can also convert Sysout.out.println () to log; All of this only requires you to click the mouse or press a shortcut key, we only think of a method to insert log as an example of the Java Editor in the context of the right button,

Select log4e, you will see the following interface: Click Insert Log Statement for this method, you will see the verification page: After finish, you will see the following function inserted into the log:

log4e more instance references http://log4e.jayefem.de

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.