Details on the use of log4j log management, which is essential for Java Development
I. Preface:
Log4j is an open source project and is a widely used logging package written in Java. Due to the outstanding performance of log4j, at the time when log4j was completed, the log4j development organization suggested that sun replace jdk1.4's log tool class with log4j in jdk1.4, but jdk1.4 was nearing completion, therefore, sun refused to use log4j. The most actually used log4j in Java Development was log4j, and Sun's log tool class was forgotten. One of its unique features includes the concept inherited in categories. By using the category hierarchy, this reduces the log record output and minimizes the overhead of log records.
It allows developers to control which log statements are output at any interval. By using an external configuration file, you can configure it at runtime. 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 provides the exact context for running the application. Once inserted into the code, no human interference is required to generate the log output. Second, log output can be saved to permanent media for future research. Finally, in addition to being used in the development phase, a wide range of log records can also be used as an audit tool.
According to this rule, in early 1996, the EU semper (European security electronic market) project decided to write its own tracking API. This API has evolved into log4j, a popular Java logging package, after numerous improvements, several implementations, and a lot of work. This package is distributed under the IBM Public License and is certified by an open source authority.
Log records have their own shortcomings. It will speed down applications. If it is too detailed, it may make the screen scroll invisible. To reduce these impacts, log4j is designed to be fast and flexible. Log4j APIs strive to be easy to understand and use because the application uses logging as the main function.
Log4j, which can control which log statements are output at any interval.
Ii. Main Components
1. Root category (at the top of the category hierarchy, that is, the global Log Level)
Configure the root logger with the Syntax:
Log4j. rootlogger = [level], appendername, appendername ,...
Level is the log record type
Appendername specifies where the log information is output. You can specify multiple output destinations at the same time.
The category level is off, fatal, error, warn, info, debug, log, all, or custom priority.
Common priorities of og4j: Fatal> error> warn> info> debug
Configure the root logger with the Syntax:
Log4j. rootlogger = [level], appendername, appendername ,...
If it is log4j. rootlogger = warn, it means that only warn, error, and fatal are output, and debug and info are blocked.
Example: log4j. rootcategory = info, stdout, runlog, errorlog
The root log category is info, debug is blocked, and others are output. Stdout, runlog, and errorlog are three output destinations respectively.
2. Common output formats
-X: left aligned when X information is output;
% P: log information level
% D {}: log generation time
% C: Location of log information (class name)
% M: log details
% N: line feed of output log information
Example:
Log4j. appender. stdout. layout. conversionpattern = % 5 P % d {yyyy-mm-dd hh: mm: SS} % C % m % N
Log4j. appender. runlog. layout. conversionpattern = % 5 P % d {yyyy-mm-dd hh: mm: SS} % C % m % N
Log4j. appender. errorlog. layout. conversionpattern = % 5 P % d {yyyy-mm-dd hh: mm: SS} % C % m % N
3. Layout
The output layout used. log4j provides four la s:
Org. Apache. log4j. htmllayout (layout in HTML form)
Org. Apache. log4j. patternlayout (you can flexibly specify the layout mode ),
Org. Apache. log4j. simplelayout (including the log information level and information string ),
Org. Apache. log4j. ttcclayout (including the log generation time, thread, category, and so on)
Example:
The output format is an HTML table.
Log4j. appender. stdout. layout = org. Apache. log4j. htmllayout
The output format is the layout mode that can be flexibly specified.
Log4j. appender. stdout. layout = org. Apache. log4j. patternlayout
The output format is the log information level and information string.
Log4j. appender. stdout. layout = org. Apache. log4j. simplelayout
The output format contains the log generation time, thread, category, and other information.
Log4j. appender. stdout. layout = org. Apache. log4j. ttcclayout
4. Destination
Configure the appender of the log output destination. Its syntax is
Log4j. appender. appendername = fully. Qualified. Name. Of. appender. Class
Log4j. appender. appendername. option1 = value1
...
Log4j. appender. appendername. Option = valuen
Appendername specifies where the log information is output. You can specify multiple output destinations at the same time.
Output destinations supported by log4j:
Org. Apache. log4j. leleappender Console
Org. Apache. log4j. fileappender File
Org. Apache. log4j. dailyrollingfileappender generates 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 stream format)
Org.apache.log4j.net. smtpappender email
Org. Apache. log4j. JDBC. jdbcappender Database
Others include GUI components, even interface servers, NT Event recorders, and Unix Syslog daemon.
Example:
Output to console
Log4j. appender. Console = org. Apache. log4j. leleappender (specify the output to the console)
Log4j. appender. Threshold = debug (specify the output category)
Log4j. appender. Console. Target = system. Out
Log4j. appender. Console. layout = org. Apache. log4j. patternlayout (specify the output layout)
Log4j. appender. console. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N (specified output format)
Output to file
Log4j. appender. File = org. Apache. log4j. fileappender (specify output to file)
Log4j. appender. file. File = file. Log (specify the output path and file name)
Log4j. appender. file. append = false
Log4j. appender. file. layout = org. Apache. log4j. patternlayout (specify the output layout)
Log4j. appender. file. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N (specified output format)
Output to a file (rotate the "Log File". When the log file reaches the specified size, the file will be closed and backed up, and a new log file will be created)
Log4j. appender. rolling_file = org. Apache. log4j. rollingfileappender (specify output to file)
Log4j. appender. rolling_file.threshold = Error (specify the output category)
Log4j. appender. rolling_file.file = rolling. Log (specify the output path and file name)
Log4j. appender. rolling_file.append = true
Log4j. appender. rolling_file.maxfilesize = 10kb (specify the size of the output file)
Log4j. appender. rolling_file.maxbackupindex = 1
Log4j. appender. rolling_file.layout = org. Apache. log4j. patternlayout (specify the output layout)
Log4j. appender. rolling_file.layout.conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N (specified in 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 (layout)
Log4j. appender. socet. layout. conversionpattern = [start] % d {date} [date] % N % P [Priority] % N % x [NDC] % N % T [thread] % N % C [Category] % N % m % N (output format)
Output to email
Log4j. appender. Mail = org.apache.log4j.net. smtpappender (specify the output to the email)
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 (recipient)
Log4j. appender. Mail. layout = org. Apache. log4j. patternlayout (layout)
Log4j. appender. mail. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N (Format)
Output to database
Log4j. appender. Database = org. Apache. log4j. JDBC. jdbcappender (specify the output to the database)
Log4j. appender. database. url = JDBC: mysql: // localhost: 3306/test (specify the database URL)
Log4j. appender. database. Driver = com. MySQL. JDBC. Driver (specify the database driver)
Log4j. appender. database. User = root (specified database user)
Log4j. appender. database. Password = root (specify the Database User Password)
Log4j. appender. database. SQL = insert into log4j (Message) values ('[framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % n') (organizes SQL statements)
Log4j. appender. database. layout = org. Apache. log4j. patternlayout (layout)
Log4j. appender. database. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N (Format)
5. Log category supplement
Sometimes we need to specify a log category different from the root category for a specific part. We can specify the priority of a package.
For example:
Log4j.category.com. Neusoft. mbip. dm. util = error, where com. Neusoft. mbip. dm. util is the part where we need to specify the log category.
Or you can specify the priority of the output file.
Log4j. appender. errorlog. Threshold = Error
Iii. Common log4j configurations
Log4j configuration is commonly used. Two methods are generally used:. properties and. xml. The following two simple examples are provided:
1. log4j. Properties
### Set the levels of info, debug, warn, error, and output location A1, A2 for the org. zblog domain ##
Log4j.category.org. zblog = error, A1
Log4j.category.org. zblog = info, A2
Log4j. appender. A1 = org. Apache. log4j. leleappender
### Set output location A1 to leleappender (console )##
Log4j. appender. a1.layout = org. Apache. log4j. patternlayout
### Set the output layout format patterlayout of A1. (you can flexibly specify the layout mode )##
Log4j. appender. a1.layout. conversionpattern = % d {yyyy-mm-dd hh: mm: SS, SSS} [% C]-[% P] % m % N
### Configure the log output format ##
Log4j. appender. A2 = org. Apache. log4j. rollingfileappender
### Set the output location A2 to the 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
# Specify HTML 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 the channel ID: org. zblog. All and the output method: org. Apache. log4j. rollingfileappender -->
<Param name = "file" value = "E:/study/log4j/all. Output. log"/> <! -- Set the file parameter: log output file name -->
<Param name = "APPEND" value = "false"/> <! -- Set whether to add a new log to the base 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 the output file project and format -->
</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 the 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 = "org. zblog. zcw"/> <! -- Corresponds to the preceding channel id -->
</Logger>
<Root> <! -- Set the channel for receiving all output -->
<Appender-ref = "org. zblog. All"/> <! -- Corresponds to the preceding channel id -->
</Root>
</Log4j: configuration>
3. 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 the. xml file
// Propertyconfigurator. Configure ("E:/study/log4j/log4j. properties"); // load the. properties File
Logger log = logger. getlogger ("org. zblog. test ");
Log.info ("test ");
}
}
4. The project uses log4j
In a web application, you can load the configuration file in a separate servlet, and configure the servlet in Web. XML to load when the application starts.
In a multi-person project, you can set an output channel for each person, so that when each person builds a logger, they can use their own domain name to let the debugging letter
Output to your own log file.
4. log4j configuration example (properties)
# Log4j. rootlogger = [level], appendername, appendername,
# The category level is off, fatal, error, warn, info, debug, log, all, or custom priority.
# Common log4j priority fatal> error> warn> info> debug
# Stdout is the console, errorlog is the error log,
Log4j. rootcategory = info, stdout, runlog, errorlog
# The output appender format is
# Log4j. appender. appendername = fully. Qualified. Name. Of. appender. Class
# Log4j. appender. appendername. option1 = value1
# Log4j. appender. appendername. Option = valuen
# Output supported by appender in log4j
# Org. Apache. log4j. leleappender Console
# Org. Apache. log4j. fileappender File
# Org. Apache. log4j. dailyrollingfileappender generates 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 stream format)
# Org.apache.log4j.net. smtpappender email
# Org. Apache. log4j. JDBC. jdbcappender Database
# Define the output format
Log4j. appender. stdout = org. Apache. log4j. leleappender
Log4j. appender. runlog = org. Apache. log4j. dailyrollingfileappender
Log4j. appender. errorlog = org. Apache. log4j. dailyrollingfileappender
# Specify the priority of the output file
Log4j. appender. errorlog. Threshold = Error
# Specify the output file
Log4j. appender. runlog. File = D: UserInfoSynWebRootWEB-INFrunlogrunlog.log
Log4j. appender. errorlog. File = D: UserInfoSynWebRootWEB-INFerrorlogerrorlog.log
# Layout of log4j
# Org. Apache. log4j. htmllayout layout in the form of HTML tables
# Org. Apache. log4j. patternlayout can flexibly specify the layout mode
# Org. Apache. log4j. simplelayout contains the log information level and information string
# Org. Apache. log4j. ttcclayout contains the log generation time, thread, category, and other information.
Log4j. appender. stdout. layout = org. Apache. log4j. patternlayout
Log4j. appender. runlog. layout = org. Apache. log4j. patternlayout
Log4j. appender. errorlog. layout = org. Apache. log4j. patternlayout
# Output format: log4j javadoc org. Apache. log4j. patternlayout
#-X: left aligned when X information is output;
# % P: log information level
# % D {}: log generation time
# % C: log information location (class name)
# % M: log details
# % N: line feed of output log information
Log4j. appender. stdout. layout. conversionpattern = % 5 P % d {yyyy-mm-dd hh: mm: SS} % C % m % N
Log4j. appender. runlog. layout. conversionpattern = % 5 P % d {yyyy-mm-dd hh: mm: SS} % C % m % N
Log4j. appender. errorlog. layout. conversionpattern = % 5 P % d {yyyy-mm-dd hh: mm: SS} % C % m % N
# Specify the priority of a package
Log4j.category.com. Neusoft. mbip. dm. util = Error
# Example
###################
# Console appender
###################
# Log4j. appender. Console = org. Apache. log4j. leleappender
# 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] %-5 p % 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 % 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] %-5 p % C % x-% m % N
# Use this layout for 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
# Specify the output layout and format
# 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] %-5 p % C % x-% m % N
####################
# 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 for 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 % N
########################
# SMTP appender
#######################
# Log4j. appender. Mail = org.apache.log4j.net. smtpappender
# Log4j. appender. Mail. Threshold = fatal
# Log4j. appender. Mail. buffersize = 10
# 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] %-5 p % 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] %-5 p % C % x-% m % n ')
# Log4j. appender. database. layout = org. Apache. log4j. patternlayout
# Log4j. appender. database. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N
########################
# Log Factor 5 appender
########################
# Log4j. appender. lf5_appender = org. Apache. log4j. lf5.lf5appender
# Log4j. appender. lf5_appender.maxnumberofrecords = 2000
###################
# Custom 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] %-5 p % C % x-% m % N
Application instance:
I used struts2 + hibernate to create a project.
Apply log4j in the following steps:
1. Import package
Test the log4j-1.2.11.jar package under Web-INF.
2. Create a properties File
Create a log4j. properties file under the src directory.
Write the configuration information (the specific configuration has been described above)
3. Create a logger object
Create a logger object in the class to be applied to log4j
Protected static final logger = logger. getlogger (imageaction. Class );
Note: import the import org. Apache. log4j. Logger package when importing the package.
4. Call the error method
In the try-Catch Block, replace the original E. printstacktrace with logger. Error ("the information to be prompted here ");
The error ("") information is printed in the C: hibernate. log file. For the convenience of searching for errors, the prompt information should be as clear as possible.
5. Run
Run the project. The information originally printed through E. printstacktrace will be printed to the hibernate. log file.