The use of log4j

Source: Internet
Author: User
Tags html form log4j

First, the foreword:
Log4j is an open source project and is widely used as a Java-written log-record package. Due to log4j's outstanding performance, when Log4j was completed, log4j development organization had recommended that Sun replace log4j's Log tool class with jdk1.4 in jdk1.4.     But at that time jdk1.4 was nearing completion, so Sun refused to use log4j, and when it was actually used most in Java development or log4j, the Sun's logging tool class was forgotten. A unique feature of it includes concepts that are inherited in categories. By using the category hierarchy, this reduces the amount of logging output and minimizes the cost of logging.

It allows developers to control which log statements are output at any interval. By using an external configuration file, it is entirely possible to configure at run time. Almost every large application includes its own logging or tracking API. Experience shows that logging is an important part of the development cycle. Similarly, logging provides some advantages. First, it can provide the exact context in which the application is run. Once inserted into the code, generating logging output does not require human intervention. Second, the log output can be saved to the permanent media for later study. Finally, in addition to being used during the development phase, a very rich log pack can also be used as an audit tool.

In accordance with this rule, in early 1996, the EU SEMPER (European Security Electronics Market) Project decided to write its own tracking API.  After countless improvements, several embodiments, and a lot of work, the API has evolved into log4j, a popular Java logging package. This package is distributed by IBM Public License and is certified by the Open Source authority.

Logging has its own drawbacks. It lowers the speed of the application.  If too detailed, it may cause the screen scrolling to become invisible. To mitigate these effects, log4j is designed to be fast and flexible. Because applications rarely treat logging as a primary feature, the log4j API strives to be easy to understand and use.
LOG4J, which controls which log statements are output at any interval.

Second, the main components

1, the root category (at the top of the category hierarchy, that is, the global log level)

Configure the root logger, whose syntax is:

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

Level is the category of the log record
Appendername is where you specify the output of the log information. You can specify multiple output destinations at the same time.

The category level is off, FATAL, ERROR, WARN, INFO, DEBUG, log, all, or custom precedence.
Og4j Common Priority Fatal>error>warn>info>debug
Configure the root logger, whose syntax is:
Log4j.rootlogger = [level], Appendername, Appendername, ...
If it is log4j.rootlogger=warn, it means that only the warn,error,fatal is exported, and Debug,info will be screened out.

Example: Log4j.rootcategory=info,stdout,runlog,errorlog
The root log category for Info,debug will be masked and the others will be output. Stdout,runlog,errorlog are 3 output destinations respectively.

2. Common output format

-X: Left-aligned when x information is output;
%p: Logging Information level
%d{}: Log Information generation time
%c: Location of log information (class name)
%m: Generated log-specific information
%n: Output log Information line wrap
Example:
log4j.appender.stdout.layout.conversionpattern=%5p%d{yyyy-mm-dd HH:mm:ss}%c%m%n
log4j.appender.runlog.layout.conversionpattern=%5p%d{yyyy-mm-dd HH:mm:ss}%c%m%n
log4j.appender.errorlog.layout.conversionpattern=%5p%d{yyyy-mm-dd HH:mm:ss}%c%m%n

3, layout
The output layout used, where log4j provides 4 layouts:
Org.apache.log4j.HTMLLayout (layout in HTML tabular format)
Org.apache.log4j.PatternLayout (You can specify layout patterns flexibly),
Org.apache.log4j.SimpleLayout (The level and information string that contains the log information),
Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, and so on that the log was generated)

Example:
Output format is HTML table
Log4j.appender.stdout.layout=org.apache.log4j.htmllayout

The output format is flexible enough to specify layout patterns
Log4j.appender.stdout.layout=org.apache.log4j.patternlayout

The output format is the level and information string that contains the log information
Log4j.appender.stdout.layout=org.apache.log4j.simplelayout

The output format contains information about the time, thread, category, and so on that the log generated
Log4j.appender.stdout.layout=org.apache.log4j.ttcclayout


4. Destination

Configure log information output destination Appender, whose syntax is


Log4j.appender.appenderName = Fully.qualified.name.of.appender.class
Log4j.appender.appenderName.option1 = value1
...
Log4j.appender.appenderName.option = Valuen
Appendername is where you specify the output of the log information. You can specify multiple output destinations at the same time.

Output destinations supported by log4j:
Org.apache.log4j.ConsoleAppender Console
Org.apache.log4j.FileAppender file
Org.apache.log4j.DailyRollingFileAppender produces a log file every day
Org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches the specified size),
Org.apache.log4j.WriterAppender (send log information to any specified place in streaming format)
Org.apache.log4j.net.SMTPAppender Mail
Org.apache.log4j.jdbc.JDBCAppender Database
Other such as GUI components, even set interface server, NT Event recorder, UNIX syslog daemon, etc.

Example:


Output to console
Log4j.appender.console=org.apache.log4j.consoleappender (Specify output to console)
Log4j.appender.threshold=debug (Specify output category)
Log4j.appender.console.target=system.out
Log4j.appender.console.layout=org.apache.log4j.patternlayout (Specify output layout)
Log4j.appender.console.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n (Specify output format)

Output to File

Log4j.appender.file=org.apache.log4j.fileappender (Specify output to file)
Log4j.appender.file.file=file.log (Specify the path and filename of the output)
Log4j.appender.file.append=false
Log4j.appender.file.layout=org.apache.log4j.patternlayout (Specifies the layout of the output)
Log4j.appender.file.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n (format of specified output)

Output to a file (rotation "log file", when the file reaches a specified size, the file is closed and backed up, and a new log file is created)

  Log4j.appender.rolling_file=org.apache.log4j.rollingfileappender (Specify output to file)
  Log4j.appender.ROLLING_FILE. Threshold=error (Specify output category)
  Log4j.appender.ROLLING_FILE. File=rolling.log (Specify the path and filename of the output)
  Log4j.appender.ROLLING_FILE. Append=true
  Log4j.appender.ROLLING_FILE. MAXFILESIZE=10KB (Specifies the size of the output to the file)
  Log4j.appender.ROLLING_FILE. Maxbackupindex=1
  log4j.appender.rolling_file.layout=org.apache.log4j.patternlayout (Specify output layout)
  Log4j.appender.rolling_file.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n (Specify output format)

Output to Socket
 log4j.appender.socket=org.apache.log4j.rollingfileappender (Specify output to socket)
  Log4j.appender.socket.remotehost=localhost (remote host)
 log4j.appender.socket.port=5001 (remote host port)
  Log4j.appender.socket.locationinfo=true
 log4j.appender.socket.layout=org.apache.log4j.patternlayout (cloth Bureau)
 log4j.appender.socet.layout.conversionpattern =[start]%d{date}[date]%n%p[priority]%n%x[ndc]%n%t[ Thread]%n%c[category]%n%m[message]%n%n (output format)

Output to mail
Log4j.appender.mail=org.apache.log4j.net.smtpappender (Specify output to mail)
  Log4j.appender.mail.threshold=fatal
 log4j.appender.mail.buffersize=10
  Log4j.appender.mail.from=chenyl@hollycrm.com (sender)
 log4j.appender.mail.smtphost= mail.hollycrm.com (SMTP server)
 log4j.appender.mail.subject=log4j message
 log4j.appender.mail.to= Chenyl@hollycrm.com (To)
 log4j.appender.mail.layout=org.apache.log4j.patternlayout (layout)
  Log4j.appender.mail.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n (format)

Output to Database
 log4j.appender.database=org.apache.log4j.jdbc.jdbcappender (Specify output to database)
  Log4j.appender.database.url=jdbc:mysql://localhost:3306/test (Specify Database URL)
 log4j.appender.database.driver =com.mysql.jdbc.driver (Specify Database Driver)
 log4j.appender.database.user=root (Specify database user)
  Log4j.appender.database.password=root (Specify database user password)
 log4j.appender.database.sql=insert into log4j (message) VALUES (' [Framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n ') (organization SQL statement)
 LOG4J.APPENDER.DATABASE.LAYOUT=ORG.APACHE.L Og4j. Patternlayout (layout)
 log4j.appender.database.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x- %m%n (format)

5, the Journal category supplement
Sometimes we need to specify a specific section of the log category that is different from the root category, and you can specify a priority for a package
Such as:
Log4j.category.com.neusoft.mbip.dm.util=error, where com.neusoft.mbip.dm.util for our needs specifically specify the section of the log category.

Or you can specify the priority of the output file
Log4j.appender.errorlog.threshold=error


Three, commonly used log4j configuration

Commonly used log4j configuration, there are generally two ways,. Properties and. XML, here are two simple examples:

1, Log4j.properties

### set Org.zblog field corresponding to the level info,debug,warn,error and Output A1,A2 # #
Log4j.category.org.zblog=error,a1
Log4j.category.org.zblog=info,a2

Log4j.appender.a1=org.apache.log4j.consoleappender
### Set Output A1, for Consoleappender (console) # #
Log4j.appender.a1.layout=org.apache.log4j.patternlayout
### sets the A1 output layout format patterlayout, (you can specify the layout mode flexibly) # #
Log4j.appender.a1.layout.conversionpattern=%d{yyyy-mm-dd hh:mm:ss,sss} [%c]-[%p]%m%n
Format of ### configuration log Output # #

Log4j.appender.a2=org.apache.log4j.rollingfileappender
### set Output A2 to file (a new file is generated when the file size reaches the specified size) # #
Log4j.appender.a2.file=e:/study/log4j/zhuwei.html
### File Location # #
log4j.appender.a2.maxfilesize=500kb
### File Size # #
Log4j.appender.a2.maxbackupindex=1
Log4j.appender.a2.layout=org.apache.log4j.htmllayout
# #指定采用html Way Output

2, Log4j.xml

<?xml version= "1.0" encoding= "GB2312"?>
<! DOCTYPE log4j:configuration SYSTEM "LOG4J.DTD" >

<log4j:configuration xmlns:log4j= "http://jakarta.apache.org/log4j/" >

<appender name= "Org.zblog.all" class= "Org.apache.log4j.RollingFileAppender"
<!--set Channel Id:o Rg.zblog.all and Output mode: Org.apache.log4j.RollingFileAppender
    <param name= "File" value= "E :/study/log4j/all.output.log "/><!--Setting the file parameter: Log output file name;
    <param name=" Append " Value= "false"/><!--setting whether to add a new log on the basis of the original log when the service is restarted;
    <layout class= Org.apache.log4j.PatternLayout "
        <param name=" Conversionpattern "value="%p (%c:%l)-%m%n "/><"!--set output file entries and formats;
    </layout>
</appender>

<appender name= "ORG.ZBLOG.ZCW" class= "Org.apache.log4j.RollingFileAppender" >
<param name= "File" value= "E:/study/log4j/zhuwei.output.log"/>
<param name= "Append" value= "true"/>
<param name= "MaxFileSize" value= "10240"/> <!--set File size-->
<layout class= "Org.apache.log4j.PatternLayout" >
<param name= "Conversionpattern" value= "%p (%c:%l)-%m%n"/>
</layout>
</appender>

<logger name= "Zcw.log" > <!--Set the domain name limit, that is, the Zcw.log domain and the following logs are output to the corresponding channel below-->
<level value= "Debug"/><!--set level-->
<appender-ref ref= "ORG.ZBLOG.ZCW"/><!--corresponds to the previous channel ID-->
</logger>

<root> <!--set the channel--> to receive all output
<appender-ref ref= "Org.zblog.all"/><!--corresponds to the previous channel ID-->
</root>

</log4j:configuration>


3, the configuration file loading method:

Import Org.apache.log4j.Logger;
Import Org.apache.log4j.PropertyConfigurator;
Import Org.apache.log4j.xml.DOMConfigurator;

public class Log4japp {
public static void Main (string[] args) {
Domconfigurator.configure ("E:/study/log4j/log4j.xml");//load. xml file
Propertyconfigurator.configure ("e:/study/log4j/log4j.properties");//load. properties file

Logger Log=logger.getlogger ("Org.zblog.test");
Log.info ("test");
}
}

4, the project uses log4j
In a Web application, you can place the load of the configuration file in a separate servlet and configure the servlet to load at application startup in Web.xml.
For a multiplayer project, you can set an output channel for each person, so that when everyone builds logger, use their own domain name, so that the debug letter
Output to its own log file.

Four, log4j configuration example (properties)

#log4j. Rootlogger = [level], Appendername, Appendername,
#类别 level is off, FATAL, ERROR, WARN, INFO, DEBUG, log, all, or custom precedence
#Log4j常用的优先级 Fatal>error>warn>info>debug

#stdout为控制台, errorlog is a log of error logging,
Log4j.rootcategory=info,stdout,runlog,errorlog


#输出的appender的格式为
#log4j. Appender.appendername = Fully.qualified.name.of.appender.class
#log4j. Appender.appenderName.option1 = value1
#log4j. appender.appenderName.option = Valuen
#Log4j中 output supported by Appender
#org. Apache.log4j.ConsoleAppender Console
#org. apache.log4j.FileAppender file
#org. Apache.log4j.DailyRollingFileAppender produces a log file every day
#org. Apache.log4j.RollingFileAppender (a new file is generated when the file size reaches the specified size),
#org. Apache.log4j.WriterAppender (send log information to any specified place in streaming format)
#org. Apache.log4j.net.SMTPAppender Mail
#org. Apache.log4j.jdbc.JDBCAppender Database

# define the form of the output
Log4j.appender.stdout=org.apache.log4j.consoleappender
Log4j.appender.runlog=org.apache.log4j.dailyrollingfileappender
Log4j.appender.errorlog=org.apache.log4j.dailyrollingfileappender


#可以指定输出文件的优先级
Log4j.appender.errorlog.threshold=error

#指定输出的文件
Log4j.appender.runlog.file=d://userinfosyn//webroot//web-inf//runlog//runlog.log
Log4j.appender.errorlog.file=d://userinfosyn//webroot//web-inf//errorlog//errorlog.log


#Log4j的layout布局
#org. apache.log4j.HTMLLayout layout in HTML form
#org. Apache.log4j.PatternLayout can specify layout patterns flexibly
#org. Apache.log4j.SimpleLayout levels and information strings that contain log information
#org. Apache.log4j.TTCCLayout contains information about the time, thread, category, and so on that the log was generated

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

#输出格式, log4j Javadoc org.apache.log4j.PatternLayout
#-x Number: X information output when left aligned;
#%p: Logging Information level
#%d{}: Log Information generation time
#%c: Location of log information (class name)
#%m: Generated log-specific information
#%n:%n: Output Log message Wrapping
log4j.appender.stdout.layout.conversionpattern=%5p%d{yyyy-mm-dd HH:mm:ss}%c%m%n
log4j.appender.runlog.layout.conversionpattern=%5p%d{yyyy-mm-dd HH:mm:ss}%c%m%n
log4j.appender.errorlog.layout.conversionpattern=%5p%d{yyyy-mm-dd HH:mm:ss}%c%m%n

#指定某个包的优先级
Log4j.category.com.neusoft.mbip.dm.util=error


#示例
###################
# Console Appender
###################
#log4j. Appender.console=org.apache.log4j.consoleappender
#log4j. Appender.threshold=debug
#log4j. appender.console.target=system.out
#log4j. appender.console.layout=org.apache.log4j.patternlayout
#log4j. Appender.console.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n
#log4j. Appender.console.layout.conversionpattern=[start]%d{date}[date]%n%p[priority]%n%x[ndc]%n%t[thread] n%c[ category]%n%m[message]%n%n


#####################
# File Appender
#####################
#log4j. Appender.file=org.apache.log4j.fileappender
#log4j. Appender.file.file=file.log
#log4j. Appender.file.append=false
#log4j. appender.file.layout=org.apache.log4j.patternlayout
#log4j. Appender.file.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n
# Use this layout to Logfactor 5 analysis

########################
# rolling File????? Rollingfileappender??????????????????
########################
#log4j. Appender.rolling_file=org.apache.log4j.rollingfileappender
# Log4j.appender.ROLLING_FILE. Threshold=error
# File Location
#log4j. Appender.rolling_file. File=rolling.log
#log4j. Appender.rolling_file. Append=true
# File Size
#log4j. Appender.rolling_file. MAXFILESIZE=10KB
#指定采用输出布局和输出格式
#log4j. Appender.rolling_file. Maxbackupindex=1
#log4j. Appender.rolling_file.layout=org.apache.log4j.patternlayout
# Log4j.appender.rolling_file.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n

The

####################
# Socket appender
####################
#log4j. appender.socket= Org.apache.log4j.RollingFileAppender
#log4j. Appender.socket.remotehost=localhost
# log4j.appender.socket.port=5001
#log4j. Appender.socket.locationinfo=true
# Set up to Log facter 5
# Log4j.appender.socket.layout=org.apache.log4j.patternlayout
#log4j. appender.socet.layout.conversionpattern= [start]%d{date}[date]%n%p[priority]%n%x[ndc]%n%t[thread]%n%c[category]%n%m[message]%n%n

########################
# SMTP appender
#######################
#log4j. appender.mail= Org.apache.log4j.net.SMTPAppender
#log4j. Appender.mail.threshold=fatal
#log4j. appender.mail.buffersize=
#log4j. appender.mail.from=chenyl@hollycrm.com
#log4j. appender.mail.smtphost=mail.hollycrm.com
# LOG4J.APPENDER.MAIL.SUBJECT=LOG4J message
#log4j. appender.mail.to=chenyl@hollycrm.com
# Log4j.appender.mail.layout=org.apache.log4j.patternlayout
#log4j. appender.mail.layout.conversionpattern=[ Framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n

########################
# JDBC Appender
#######################
#log4j. Appender.database=org.apache.log4j.jdbc.jdbcappender
#log4j. appender.database.url=jdbc:mysql://localhost:3306/test
#log4j. Appender.database.driver=com.mysql.jdbc.driver
#log4j. Appender.database.user=root
#log4j. appender.database.password=
#log4j. Appender.database.sql=insert into log4j (message) VALUES (' [Framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n ')
#log4j. appender.database.layout=org.apache.log4j.patternlayout
#log4j. Appender.database.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n

########################
# Log Factor 5 Appender
########################
#log4j. Appender.lf5_appender=org.apache.log4j.lf5.lf5appender
#log4j. Appender.lf5_appender. maxnumberofrecords=2000

###################
#自定义Appender
###################
#log4j. appender.im = Net.cybercorlin.util.logger.appender.IMAppender
#log4j. appender.im.host = mail.cybercorlin.net
# Log4j.appender.im.username = Username
#log4j. Appender.im.password = password
#log4j. appender.im.recipient = Corlin@cybercorlin.net
#log4j. Appender.im.layout=org.apache.log4j.patternlayout
# Log4j.appender.im.layout.ConversionPattern =[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n  

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.