log4j log File

Source: Internet
Author: User
Tags html form log log pack print format log4j

Log processing is a necessary feature in every project development, and logs are running information that is recorded in other files while the program is running.

There are three purposes for exporting logs in an application:

1 Monitor the change of variables in the code, periodically record the data to the file for other applications for statistical analysis work.

2 tracking code run time trajectory, as the basis for future audits.

3 acts as a debugger in an integrated development environment, printing code debugging information to a file or controller.

The user is free to choose to implement the log interface of Third-party software, such as: log4j, Nooplog, Simplelog, etc. are the implementation of the common Log package.

Log file action: is a logger for recording the various information in the process of running the program.
Log configuration: Sets the level of the record, where it is stored, and the layout of the information displayed. Can be configured using the Log4j.properties or log4j.xml format.

Log4j.properties:

To load the Log4j.properties step:

1: Put the log4j jar package into the Lib directory

2: Put the log4j.properties file in the SRC directory

3: Import the class into the class import Org.apache.log4j.Logger;

4: Define objects in the class logger logger = Logger.getlogger (This.getclass ());

5: Use logger output log logger.info (string);

The Apache Common Log Pack (log4j, download address: http://logging.apache.org/log4j) is an open source code project for Apache, which provides a common set of log interfaces, The two commonly used interfaces in a common log pack are logfactory and log.

The common log packet divides log messages into six levels:

FATAL (Fatal level), error (Fault level), WARN (Warning level), INFO (General information), debug (debug information), and Trace (trace information).

With the highest fatal level and the lowest trace level, the common log packet uses a log-level mechanism to control the output log content flexibly.

The Org.apache.commons.logging.Log interface provides the following methods for outputting different levels of logging.

Method Name

Description

Fatal (Object message)

Output fatal-level log messages

Error (Object message)

Output error-level log messages

Warn (Object message)

Output warn-level log messages

Info (Object message)

Output info-level log messages

Debug (Object message)

Output debug-level log Messages

Trace (Object message)

Output trace-level log messages

LOG4J allows us to control the destination of log information delivery, such as console, file, GUI components, UNIX syslog daemon, etc., and allow us to control the output format of each log, by defining the level of each log information (Fatal,error,warn,info, Debug), we are able to control the log generation process in more detail. At the same time, these can be flexibly configured with a single configuration file without the need to modify the applied code.

log4j configuration file content consists of three major components:

①logger: Responsible for generating logs, and according to the configured log level to determine what log messages should be output, than the specified level of high log information can be output, such as the designated day level for info, then info, WARN, ERROR, fatal log can be output.

②appender: Defines the destination of the log message output, specifying where the log message should be exported, either a console, a file, or a network device.

③layout: Specifies the output format of the log message.

The log4j configuration file has two formats, one is an XML file, the other is a properties file. The following is the form of a properties file for log configuration. The definition profile name is log4j.properties and placed under the classes directory.


1 Configuring Logger Components

To configure the syntax for the logger component:

Format:
#log4j. rootlogger= log level, Appender name 1, appender name 2,...
Description
A, the level is: fatal > Error > Warn > Info > Debug > Trace
b, the location list is separated by commas, which are the descriptions of the variables (which need to be referenced when you configure the output destinations below)
Attention:
If the level is info, then records that are greater than or equal to info are recorded, and are less than the info level (other levels are similar).

#其中日志级别可以是前面定义的六种级别中的一种, the Appender name can be any valid identifier.

#可以是一个, or multiple, the log levels configured below are Info,appender names A1 and R: Code: Log4j.rootlogger=info, A1, R


2 is configured for logger appender, configuring the log message output destination Appender, whose syntax is:

Format:
Log4j.appender. Store position variable = The fully qualified name of the storage location class (typically provided by the log4j component) ①
Log4j.appender. Store position variable. Attribute = property value
Description
A, LOG4J provides several classes corresponding to the storage location
1, Org.apache.log4j.ConsoleAppender (console)
2, Org.apache.log4j.FileAppender (file)
3, Org.apache.log4j.DailyRollingFileAppender (produce a log file every day)
4, Org.apache.log4j.RollingFileAppender (when the file reaches a certain size, it will produce a new file)
5, Org.apache.log4j.WriterAppender (log stream, you can log messages in streaming format sent to any designated place)
B, File property
You can set the specific file name of the output
C, Threshold properties
You can set the level of output

Code: Log4j.appender.a1=org.apache.log4j.fileappender
Log4j.appender.a1.file=c:/log4j.htm②

①LOG4J offers the following types of Appender: such as: Upper A.

② log output to c:/log4j.htm file

3 Configure the layout component to configure the syntax of the layout component:

Format:
Log4j.appender. Store position variable. Layout = Fully qualified name of the layout class (typically provided by the log4j component) ①
Log4j.appender. Store position variables. layout. Attribute = property value
Description
A, LOG4J provides several classes corresponding to the layout
1, org.apache.log4j.HTMLLayout (in HTML form layout)
2, Org.apache.log4j.PatternLayout (in the specified mode of layout, by setting properties can be flexible to specify layout mode)
3, Org.apache.log4j.SimpleLayout (simple layout, contains the level and information string)
4, Org.apache.log4j.TTCCLayout (including the time, thread, category and other information layout)
b, parameters for the Conversionpattern property in the layout:

LOG4J uses a print format similar to the printf function in c to format the log information, printing parameters 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 The name of the thread that generated the log event

%n output a carriage return line feed, Windows platform "RN", UNIX platform "n"

%d output log point-in-time date or time, the default format is ISO8601, you can also specify the format after, such as:%d{yyyy MMM dd hh:mm:ss,sss}, output similar: October 18, 2002 22:10:28,921

%l the location where the output log event occurs, including the class name, the thread that occurred, and the number of lines in the code.

#例如:

Log4j.appender.a1.layout=org.apache.log4j.htmllayout LOG4J.APPENDER.R.LAYOUT.CONVERSIONPATTERN=%-D{HH:MM:SS} [%c ]-[%P]%m%n②

In tomcat, a generic Log Interface Pack (Commons-logging.jar) is brought in, and log4j configuration information is automatically loaded as long as a log4j.properties file exists in the classes directory. Log output is booted by log4j with a common log pack. Therefore, you do not need to configure the common log interface, the common Log interface configuration file should be placed in the/web-inf/classes directory, the file name is: commons-logging.properties, the configuration code is as follows:

To configure the syntax for a common log pack: #org. apache.commons.logging.log= implementation class fully qualified name

For example:

#比如, the implementation class for log4j is: Org.apache.commons.logging.log=org.apache.commons.logging.impl.log4jcategorylog

☆: The use of log4j in a program can be accessed through its own APIs or by using a common log packet interface.

//Common Log Pack Usage

//import: Org.apache.commons.logging.Log

//import: Org.apache.commons.logging.LogFactory

Log Log=logfactory.getlog (This.getclass ());

log.debug ("Debug ...");

log.info ("info .... ...");

 

//log4j own API use

//import Org.apache.log4j.Logger

Logger Logger = Logger.getlogger (This.getclass ());

logger.debug ("Debug ..."); logger.info ("info .... ...");Common configurations:
Configuration 1:
#配置根: Og4j.rootlogger=debug,a1,r
#配置控制台输出:
Log4j.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,sss} [%c]-[%p]%m%n
#配置每天一个日志文件:
Log4j.appender.r=org.apache.log4j.dailyrollingfileappender
Log4j.appender.r.file=blog_log.txt
log4j.appender.r.maxfilesize=500kb
log4j.appender.r.maxbackupindex=10
Log4j.appender.r.layout=org.apache.log4j.patternlayout
Log4j.appender.r.layout.conversionpattern=%d{yyyy-mm-dd hh:mm:ss,sss} [%t] [%c] [%p]-%m%n
Configuration 2:
Log4j.rootlogger=debug,console,file,rolling_file,mail,database
Log4j.addivity.org.apache=true
###################
# console Configuration
###################
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[level]%n%x[loop diagnostics Environment]%n%t[thread] n%c[class]%n%m[message] %n%n
#####################
# File Configuration
#####################
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
########################
# every day a log file is configured
########################
Log4j.appender.rolling_file=org.apache.log4j.rollingfileappender
Log4j.appender.ROLLING_FILE. Threshold=error
Log4j.appender.ROLLING_FILE. File=rolling.log
Log4j.appender.ROLLING_FILE. Append=true
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
########################
# Mail configuration (requires JavaMail and JAF support)
#######################
Log4j.appender.mail=org.apache.log4j.net.smtpappender
Log4j.appender.mail.threshold=fatal
log4j.appender.mail.buffersize=10
Log4j.appender.mail.from=iambenbenchen@163.com
Log4j.appender.mail.smtphost=mail.163.com
LOG4J.APPENDER.MAIL.SUBJECT=LOG4J message
Log4j.appender.mail.to=iambenbenchen@163.com
Log4j.appender.mail.layout=org.apache.log4j.patternlayout
Log4j.appender.mail.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n
########################
# database configuration (MySQL, note: No spaces after each line, or error)
#######################
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= Root
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
Sample code:

Import Org.apache.commons.logging.Log;
Import Org.apache.commons.logging.LogFactory;
Import Org.apache.log4j.Logger;

public class loginaction{

Log Log=logfactory.getlog (This.getclass ());
Logger Logger = Logger.getlogger (This.getclass ());


public void Method () {
Log.info (Userinfo.getuserinfo (). GetUserName () + "Log_info started landing");
Logger.info (Userinfo.getuserinfo (). GetUserName () + "Logger_info started landing");
}
}

public class Loginservlet extends httpservlet{

public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {

...

Logger Logger=logger.getlogger (This.getclass ());
Logger.info (name+ "Start login");

...

Logger.info (name+ "Login Failed" +e.getmessage ());

...

Logger.info (name+ "Login Successful");

...

}

}

Log4j.properties file:

### Direct log messages to stdout ###
Log4j.appender.stdout=org.apache.log4j.consoleappender
Log4j.appender.stdout.target=system.out
Log4j.appender.stdout.layout=org.apache.log4j.patternlayout
Log4j.appender.stdout.layout.conversionpattern=%d{absolute}%5p%c{1}:%l-%m%n

### Direct messages to file Hibernate.log ###
#log4j. Appender.file=org.apache.log4j.fileappender
#log4j. Appender.file.file=hibernate.log
#log4j. appender.file.layout=org.apache.log4j.patternlayout
#log4j. Appender.file.layout.conversionpattern=%d{absolute}%5p%c{1}:%l-%m%n

#定义一个名字为file的Appender, its type is rollingfileappender.
Log4j.appender.file=org.apache.log4j.rollingfileappender
#设置最大文件尺寸为1MB, start backing up to backup files when the log file size reaches 1MB
Log4j.appender.file.maxfilesize=1mb
#设置备份文件的最大数目为1024个文件, more than 1024 will automatically delete the oldest files
log4j.appender.file.maxbackupindex=1024
#指定file the name and storage path of the log file Appender output.
Log4j.appender.file.file=d\:/salog4j.log
Log4j.appender.file.layout=org.apache.log4j.patternlayout
Log4j.appender.file.layout.conversionpattern=%d{yyyy-mm-dd HH:MM:SS} [%c]-[%-5p]%m%n%n

### set Log levels-for more verbose logging change ' info ' to ' debug ' ###

Log4j.rootlogger=info, File

#log4j. Logger.org.hibernate=info
#log4j. Logger.org.hibernate=debug

### Log HQL Query parser activity
#log4j. Logger.org.hibernate.hql.ast.ast=debug

### Log just the SQL
#log4j. Logger.org.hibernate.sql=debug

### log JDBC bind parameters ###
#log4j. Logger.org.hibernate.type=info
#log4j. Logger.org.hibernate.type=trace

### Log Schema Export/update ###
#log4j. Logger.org.hibernate.tool.hbm2ddl=debug

### Log HQL Parse trees
#log4j. Logger.org.hibernate.hql=debug

### Log Cache Activity ###
#log4j. Logger.org.hibernate.cache=debug

### Log Transaction activity
#log4j. Logger.org.hibernate.transaction=debug

### Log JDBC Resource acquisition
#log4j. Logger.org.hibernate.jdbc=debug

### enable the following line if your want to track down connection ###
### leakages when using Drivermanagerconnectionprovider ###
#log4j. Logger.org.hibernate.connection.drivermanagerconnectionprovider=trace


log4j.xml configuration File Settings

<?xml version= ' 1.0 ' encoding= ' UTF-8 '
<! DOCTYPE log4j:configuration SYSTEM "Log4j.dtd" "
<log4j:configuration xmlns:log4j=" http:// jakarta.apache.org/log4j/""
<appender class= "Org.apache.log4j.DailyRollingFileAppender" Name= " Rollingfile ""
<param name= "Datepattern" value= "Yyyy-mm-dd"
/> <param "File" Name= "value= Log.log "/>
<param name=" Encoding "value=" GBK "/>
<layout class=" Org.apache.log4j.PatternLayout "
<param name= "Conversionpattern" value= "%d%-5p%-5c{3}:%l%x{client}-&gt;%m%n"/>
</layout
</appender>
<logger name= "Com.lovebay"
<level value= "DEBUG"/>

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.