Spring configuration log4j and a brief introduction to the use of log4j

Source: Internet
Author: User
Tags java open source projects

LOG4J is an Apache open source project, through the use of log4j, we can control the log information delivery destination is the console, files, GUI components, even the socket server, NT Event recorder, UNIX syslog daemon, etc. We can also control the output format of each log, and by defining the level of each log information, we can control the log generation process more carefully. Most interesting of all, these can be configured flexibly with a single configuration file, without the need to modify the code of the application.

Such a powerful superiority, in fact, the hand is not difficult, especially in the spring framework, the use of log4j is easier, the following describes the log4j application under spring.

Of course, first download the corresponding jar package (Log4j.jar)

First, the configuration of Web. XML, add the following configuration in Web. xml

<context-param>
<param-name> log4jconfiglocation</param-name>
<param-value>/WEB-INF/props/log4j.properties</param-value>
</context-param>
<context-param>
<param-name> log4jrefreshinterval</param-name>
<param-value>6000</param-value>
</context-param>


<listener>
<listener-class>
Org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>


Note: In the above configuration, in the above configuration, Log4jconfiglistener will go to web-inf/props/log4j.propeties read the configuration file; Open a watchdog thread scans every 60 seconds for changes in the configuration file (so that the Web service starts and then modifies the configuration file without restarting the Web service); The path to the Web directory is pressed into a system variable called Webapp.root (Webapp.root will be used in the Log4j.properties file).

Next is the log4j.properties configuration file, put it under the Web-inf/props, the specific configuration is as follows:

#log4j. Rootlogger = [level], Appendername, Appendername, ...
Log4j.rootlogger = INFO, console, R
#level =info,all can be output
#console is set to be a Consoleappender
Log4j.appender.console = Org.apache.log4j.ConsoleAppender
#console has four patterns
#org. apache.log4j.HTMLLayout
#org. apache.log4j.PatternLayout
#org. apache.log4j.SimpleLayout
#org. apache.log4j.TTCCLayout
Log4j.appender.console.layout = Org.apache.log4j.PatternLayout
#define The output type
Log4j.appender.console.layout.ConversionPattern =%-d{yyyy-mm-dd HH:mm:ss} [%c]-[%p]%m%n
#file is set to output to a extra file
LOG4J.APPENDER.R = Org.apache.log4j.RollingFileAppender
#the Absolute route of the log4j file
Log4j.appender.r.file =/log.txt
#the size
Log4j.appender.r.maxfilesize = 500KB
#back up a file
Log4j.appender.r.maxbackupindex = 1
Log4j.appender.r.layout = Org.apache.log4j.PatternLayout
Log4j.appender.r.layout.conversionpattern=%-d{yyyy-mm-dd HH:MM:SS} [%c]-[%p]-%m%n

The above configuration file indicates that the log information will be output in two ways (file and console), indicating the root directory of the app (for example, this app name is ABC, then Log.txt is located under TOMACT\WEBAPP\ABC)

Finally add log4j support where you want to output log in the program

(1) Importing import Org.apache.log4j.Logger

(2) Declaring a logger

private static Logger Logger = Logger.getlogger (Classname.class);

(3) Add the output information in the corresponding position in the program

logger. info ("User login:" +user.getaccount ());

OK, finished, when there is login will be in the console and file output log information as follows

2007-01-10 16:02:54 [com.my.web.useraction]-[info] User login: YANGSQ

PS:


As a popular logging tool, log4j is one of the brightest links in Java open source projects. The following are some of the reasons for this:

A) log4j is embraced by most Web application servers: As far as I know, Tomcat,weblogic,websphere,jboss supports log4j.

b) Fast and powerful: The log4j configuration file implements a full set of functions such as output to console, file, rollback file, send log mail, output to database log table, custom label, etc. In the speed, from the beginning of the log4j, the focus on the speed of operation has been put in the first place, and continue to improve and improve.

c) Easy and convenient to use: simply import a simple log4j-1.2.x.jar, then write the following sentence at the beginning of the program class private final static Logger log =logger.getlogger ( Classname.class);

This gives you a log object that can easily write logs to a specific target.

Why do I need log4j? Commissioning of---Project is the intrinsic driving force generated by log4j

The original method is to output the information to the screen (console), using the System.out.println provided by the JDK. However, the disadvantage of doing so is obvious:

A) The output of the information is not flexible and cumbersome. For example, to output the file name of the execution, the number of rows, the current time, and so on, println appears very primitive.

b) If you want to change the content and format of the output, you need to recompile the source program.

c) More serious, if there are many println in the program, it will seriously affect the performance of the program.

Log4j several key points to use?

Root logger (rootlogger), Output (appenders) and layout (layouts)

A) define the root logger format as

Log4j.rootlogger = [level], appendName1, appendName2, ... appendnamen. The same logger can have multiple outputs.

Ps:level level (This level can be customized, the system provides the following levels by default)

debug//Debugging Information

info//General Information

warn//warning message

error//error message

fatal//Fatal error message

Listed above is the so-called log4j output level, log4j recommended to use only 4 levels, they are error, WARN, INFO, DEBUG, respectively, from top to bottom, assuming that you define the level is INFO, Then the error and warn logs can be displayed and the debug information lower than him is not displayed.

b) Define a Appender output destination in the format

Log4j.appender.appenderName = Fully.qualified.name.of.appender.class. The log4j provides several common output destinations:

Org.apache.log4j.ConsoleAppender, output log information to the console

Org.apache.log4j.FileAppender, output log information to a file

Org.apache.log4j.DailyRollingFileAppender, output log information to one, and output to a new log file daily

Org.apache.log4j.RollingFileAppender, the log information output to a file, by specifying the size of the file, when the size of the file to reach the specified size will automatically rename the file, such as a file named Example.log will be renamed to Example.log.1 and generate a new Example.log file. If the new file reaches the specified size again, it will automatically rename the file to example.log.2 and produce a example.log file. And so on until Example.log. Maxbackupindex, the value of Maxbackupindex can be defined in the configuration file.

Org.apache.log4j.WriterAppender, sends the log information in stream format to any specified place.

Org.apache.log4j.jdbc.JDBCAppender, the log information is exported to the database through JDBC.

c) Layout of output format (layout)

LOG4J provides several layouts:

Org.apache.log4j.HTMLLayout, layout in HTML table format

Org.apache.log4j.PatternLayout with flexibility to specify layout mode

Org.apache.log4j.SimpleLayout, which contains the level and information string for log information

The statement that defines a patternlayout layout is:

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

Log4j.appender.stdout.layout.conversionpattern=%d{absolute}%5p%c{1}-%m%n

The format meaning of the Ps:conversionpattern parameter

The full name of the class to which the%c output log information belongs

%d the date or time of the output log time, the default format is ISO8601, or the format can be specified later, for example:%d{yyy-mm-dd HH:mm:ss}, output similar to: 2002-10-18-22:10:28

%f the class name of the class to which the output log information belongs

%l the occurrence of the output log event where the statement that outputs the log information is in the first line of the class it is in

%m the information specified in the output code, such as a message in log (message)

%n output a carriage return newline character, Windows platform is "\ r \ n", Unix platform is "\ n"

%p output priority, or debug,info,warn,error,fatal. Debug if the debug () output is called, and so on

%r the number of milliseconds that the output from the application starts to output this log information

%t output The name of the thread that generated the log event

Configuration file for log4j: log4j.properties

An example of a log4j.properties file

Log4j.rootlogger=info, stdout, logfile

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=/webserver/specialtraining3/wangzj.log

log4j.appender.logfile.maxfilesize=51200kb

Log4j.appender.logfile.maxbackupindex=3

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

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



Spring configuration log4j and a brief introduction to the use of log4j

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.