Log4j component composition
Log4j consists of three important components:
1. Priority of log information (Logger)
2. The output destination of log information (Appender)
3. Output format (Layout) of log information.
summary:
The priorities of log information from high to low include ERROR, WARN, INFO, and DEBUG, which are used to specify the importance of this log information respectively;
The output destination of the log information specifies whether the log will be printed to the console or a file;
The output format controls the display content of the log information.
Log4j introduction
Log4j is an open source project of Apache. By using Log4j, we can control the destination of log information transmission to consoles, files, GUI components, and even socket servers, NT event recorders, UNIX Syslog daemons, etc.; We can also control the output format of each log. By defining the level of each log information, we can control the log generation process in more detail. log4j-- log for java (java log).
Log4j download address: http://logging.apache.org/log4j/2.x/download.html
Log4j configuration file format
Log4j supports two configuration file formats:
1. XML format files
2. Files in properties format
You can also not use the configuration file at all, but configure the Log4j environment in code. However, using configuration files will make your application more flexible.
Log4j definition configuration file
1. Configure the root Logger
Its syntax is:
Parameter description:
level is the priority of logging, which is divided into OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL or the level you define.
Off: the highest level, used to turn off all logging
Fatal: Indicates that each fatal error event will cause the application to exit.
Error: indicates that although an error event occurs, it still does not affect the continued operation of the system.
Warn: Indicates that a potential error situation will occur
Info: Generally used at the coarse-grained level, emphasizing the entire running process of the application
Debug: Generally and at a coarse-grained level, emphasizing the entire running process of the application.
All: The lowest level, used to turn on all logging.
Log4j recommends using only four levels. The priorities from high to low are ERROR, WARN, INFO, and DEBUG. Through the levels defined here, you can control the on and off of the corresponding level of log information in the application.
appenderName refers to where the log information is output, and multiple output destinations can be specified at the same time.
2. Configure the log information output destination Appender
Its syntax is:
log4j.appender.appenderName.option1 = value1
...
log4j.appender.appenderName.option = valueN
org.apache.log4j.ConsoleAppender(Console)
org.apache.log4j.FileAppender(File)
org.apache.log4j.DailyRollingFileAppender (generates a log file every day)
org.apache.log4j.RollingFileAppender (generates a new file when the file size reaches the specified size)
org.apache.log4j.WriterAppender (sends log information in streaming format to any specified place)
3. Configure the format of log information
The syntax is:
log4j.appender.appenderName.layout.option1 = value1 …
log4j.appender.appenderName.layout.option = valueN
org.apache.log4j.HTMLLayout (layout in HTML table format),
org.apache.log4j.PatternLayout (can flexibly specify layout patterns),
org.apache.log4j.SimpleLayout (contains the level and information string of the log information),
org.apache.log4j.TTCCLayout (contains log generation time, thread, category, etc. information)
Log4J uses a printing format similar to the printf function in C language to format log information. The printing parameters are as follows:
%mOutput the message specified in the code
%p output priority, namely DEBUG, INFO, WARN, ERROR, FATAL
%r outputs the number of milliseconds it took from the start of the application to the output of the log information.
%c outputs the category to which it belongs, usually the full name of the class.
%tOutput the name of the thread that generated the log event
%n outputs a carriage return and line feed character, which is "rn" on the Windows platform and "n" on the Unix platform.
%d outputs the date or time of the log time point. The default format is ISO8601. You can also specify the format afterwards, such as: %d{yyyMMMddHH:mm:ss,SSS}. The output is similar: October 18, 2002 22:10 :28,921
%l Outputs the location where the log event occurred, including the category name, the thread where it occurred, and the line number in the code. Example: Testlog4.main(TestLog4.java:10)
%x: Outputs the NDC (nested diagnostic environment) associated with the current thread, especially used in multi-client and multi-thread applications like javaservlets.
%%: Output a "%" character %F: Output the file name where the log message is generated
%L: Line number in the output code
%m: Output the message specified in the code and the specific log information generated
%n: Outputs a carriage return and line feed character, which is "/r/n" on the Windows platform and "/n" on the Unix platform. When outputting log information, you can add modifiers between % and the mode character to control its minimum width and maximum width. Width, and text alignment.
like:
1)%20c: Specify the name of the output category. The minimum width is 20. If the category name is less than 20, it will be right-aligned by default.
2)%-20c: Specify the name of the output category. The minimum width is 20. If the category name is less than 20, the "-" sign specifies left alignment.
3)%.30c: Specify the name of the output category. The maximum width is 30. If the category name is greater than 30, the extra characters on the left will be cut off, but if it is less than 30, there will be no spaces.
4)%20.30c: If the category name is less than 20 characters, fill in spaces and right-justify it. If the name is longer than 30 characters, truncate the characters from the left side.
Configuration method of log4j.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="appender1"
>
<param name="File" value="logfile08.html" />
<param name="MaxFileSize" value="1MB" />
<param name="MaxBackupIndex" value="5" />
<layout>
</layout>
</appender>
<root>
<level value="debug" />
<appender-ref ref="appender1" />
</root>
</log4j:configuration>
Before using Log4j in the program, first import commons-logging.jar and logging-log4j-1.2.9.jar into the classpath, and put log4j.properties in the src root directory. To use log4j in a class, first declare a static variable Loggerlogger=Logger.getLog("classname"). It can be used now.
The usage is as follows: logger.debug("debugmessage") or logger.info("infomessage").
1. Get the logger
Using Log4j, the first step is to obtain a logger, which will be responsible for controlling log information.
Its syntax is:
publicstaticLoggergetLogger(Stringname)
Gets the logger by the specified name and, if necessary, creates a new logger for that name. Name generally takes the name of this class, such as:
staticLoggerlogger=Logger.getLogger(ServerWithLog4j.class.getName())
2. Read the configuration file
After obtaining the logger, the second step is to configure the Log4j environment. The syntax is:
BasicConfigurator.configure(): Automatically and quickly use the default Log4j environment.
PropertyConfigurator.configure(StringconfigFilename): Read the configuration file written using Java's property file.
DOMConfigurator.configure(Stringfilename): Read the configuration file in XML form.
3. Insert record information (formatted log information)
When the above two necessary steps are completed, you can easily use logging statements with different priorities to insert anywhere you want to log. The syntax is as follows:
Logger.debug(Objectmessage);
Logger.info(Objectmessage);
Logger.warn(Objectmessage);
Logger.error(Objectmessage);
Program demonstration
1. Use a program to output log information
import java.io.IOException;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
/**
*
* @version: 1.1
*
* @author: Su Ruonian<a href="mailto:[email protected]">Send email</a>
*
* @since: 1.0 Creation time: 2013-1-1 03:19:42 pm
*
* @function: Output the log through code
*
*/
public class Log4jPrintByCode {
private static Logger logger = Logger.getLogger(Log4jPrintByCode.class);
private Layout layout = new SimpleLayout();
private FileAppender fileAppender;
//Use construction dependencies and initialize when creating objects
public Log4jPrintByCode(Layout layout, Level level,String distDir){
BasicConfigurator.configure(); //Use default configuration information, no need to write log4j.properties
try {
init(layout,level, distDir);
} catch (Exception e) {
e.printStackTrace();
}
}
public void init(Layout layout, Level level,String distDir) throws Exception{
logger.setLevel(level); //Set the log output level
fileAppender = new FileAppender(layout,distDir,false);
logger.addAppender(fileAppender); //Add output terminal
}
public static void main(String[] args) {
SimpleLayout layout = new SimpleLayout();
String logDir = "log4jcode.Log";
Log4jPrintByCode log4jCode = new Log4jPrintByCode(layout,Level.INFO,logDir);
//The following information will be output
log4jCode.logger.info("log info print by log4j");
log4jCode.logger.warn("log warn print by log4j");
log4jCode.logger.error("log error print by log4j");
}
public Layout getLayout() {
return layout;
}
public void setLayout(Layout layout) {
this.layout = layout;
}
public FileAppender getFileAppender() {
return fileAppender;
}
public void setFileAppender(FileAppender fileAppender) {
this.fileAppender = fileAppender;
}
}
// Record info level information
if (logger.isInfoEnabled()) {
logger.info("This is info message from Dao.");
}
2.Log4J outputs the same log information to multiple destinations
/* Switch database */
use db_log4j;
/* Log information table */
create table tb_log(
logId int not null auto_increment comment 'serial number',
createDate varchar(45) default null comment 'Log generation time',
thread varchar(45) default null comment 'current thread',
level varchar(45) default null comment 'Current log level',
class varchar(45) default null comment 'Generate log class',
message varchar(245) default null comment 'Log specific information',
primary key(logId)
);
The application instance outputs log information to the console, file and database at the same time.
Create database and tables
/* Switch database */
use db_log4j;
/* Log information table */
create table tb_log(
logId int not null auto_increment comment 'serial number',
createDate varchar(45) default null comment 'Log generation time',
thread varchar(45) default null comment 'current thread',
level varchar(45) default null comment 'Current log level',
class varchar(45) default null comment 'Generate log class',
message varchar(245) default null comment 'Log specific information',
primary key(logId)
);
#Define A1 output to the controller
log4j.appender.A1=org.apache.log4j.ConsoleAppender
#Define the layout mode of A1 as PaternLayout
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
# Define the output format of A1
log4j.appender.A1.layout.ConversionPattern=%4p [%t] (%F:%L) - %m%n
#Define A2 output to file
log4j.appender.A2=org.apache.log4j.RollingFileAppender
#Define which file A2 outputs to
log4j.appender.A2.File=./log/sysLog.log
#Define the maximum length of the A2 output file
log4j.appender.A2.MaxFileSize = 1KB
#Define the number of backup files for A2
log4j.appender.A2.MaxBackupIndex = 3
#Define the layout mode of A2 as PatternLayout
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
#Define the output mode of A2
log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm:ss}:%p %t %c - %m%n
#Define A3 output to the database
log4j.appender.A3=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.A3.URL=jdbc:mysql://localhost:3306/db_log4j
log4j.appender.A3.driver=com.mysql.jdbc.Driver
log4j.appender.A3.user=root
log4j.appender.A3.password=root
#Define the layout of A3 and the SQL statements executed
log4j.appender.A3.layout=org.apache.log4j.PatternLayout
log4j.appender.A3.layout.ConversionPattern=INSERT INTO tb_log(createDate,thread,level,class,message) values('%d','%t','%-5p','%c','%m ')
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
*
* @version: 1.1
*
* @author: Su Ruonian<a href="mailto:[email protected]">Send email</a>
*
* @since: 1.0 Creation time: 2013-1-1 04:13:59 PM
*
* @function: Control the output of log information to multiple destinations through configuration files
*
*/
public class Log4jPrintByConfigure {
private static Logger logger = Logger.getLogger(Log4jPrintByConfigure.class);
public static void main(String[] args) throws Exception {
//Load the log configuration file log4j.properties
PropertyConfigurator.configure("configure/log4j.properties");//The file is stored in the configure folder in the same directory as src
//If placed under src, the parameters should be "bin/log4j.properties" or "src/log4j.properties". It is recommended to use bin as the standard.
//The following information will be printed out
logger.debug("logger print DEBUG messgae");
logger.info("logger print INFO message");
logger.warn("logger print WARN message");
logger.error("logger print ERROR message");
logger.fatal("Here is FATAL message");
}
}