Use Log4j to configure the log output for the project with the detailed application and implementation analysis demonstrated by the example

  • 2020-04-01 01:55:25
  • OfStack

Log4j components  

Log4j consists of three important components:

1. Priority of log information (Logger)

2. Output destination of log information (Appender)

3. Output format of log information (Layout).

Summary:

The priority of log information from high to low is ERROR, WARN,   INFO and DEBUG, respectively, are used to specify the importance of this log information.

The output destination of the log information specifies whether the log will be printed to the console or to a file;

The output format controls the display of log information.

Log4j is introduced

Log4j is an open source project of Apache. By using Log4j, we can control the destinations of log information delivery to the console, files, GUI components, even the interface server, NT event logger, UNIX Syslog daemon, etc. We can also control the output format of each log, and by defining the level of each log message, we can control the log generation in more detail. Log4j -- log for Java.

Log4j download address: (link: http://logging.apache.org/log4j/2.x/download.html)

The format of the Log4j configuration file

Log4j supports two configuration file formats:

1. File in XML format

2. File in properties format

You can also configure the Log4j environment in your code without using configuration files at all. However, using configuration files makes your application more flexible.

Log4j defines the configuration file

1. Configure the root Logger

Its syntax is:


log4j.rootLogger = [ level ] , appenderName, appenderName,  ... 

Parameter description:

Level  Is the priority of logging, classified as OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL, or whatever level you define.

Off:   Highest level, used to close all logging

Fatal:   Indicate that each serious error event will cause the application to exit.

Error:   Indicates that although an error event occurred, it still does not affect the continuation of the system.

Warn:   Indicates a potential error situation

Info:   Generally used at the coarse-grained level to emphasize the entire run of the application

The Debug:   In general and at the coarse-grained level, the emphasis is on the application's journey.

All:   Lowest level, used to turn on all logging.

Log4j recommends using only four levels, with the highest to lowest priority being ERROR, WARN, INFO, and DEBUG. With the level defined here, you can control the switch to log information at the appropriate level in the application.

AppenderName simply means where the log information is output, and you can specify multiple output destinations at the same time.

2. Configure an Appender to output log information

Its syntax is:


log4j.appender.appenderName = fully.qualified.name.of.appender.class   
log4j.appender.appenderName.option1 = value1   
...   
log4j.appender.appenderName.option = valueN

Log4j provides several appenders:

Org, apache log4j. ConsoleAppender (console)

Org, apache log4j. FileAppender (file)

Org, apache log4j. DailyRollingFileAppender (every day to create a log file)

Org, apache log4j. RollingFileAppender (file size arrived in time to generate new file) of the specified size

Org, apache log4j. WriterAppender (the log information to flow format to send to any designated place)

 

3. Configure the format of the log information

Grammar:


log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class 
log4j.appender.appenderName.layout.option1 = value1  ...  
log4j.appender.appenderName.layout.option = valueN

Log4j provides several layouts:

Org, apache log4j. HTMLLayout (layout) in HTML form,

Org, apache log4j. PatternLayout (the flexibility to specify layout model),

Org, apache log4j. SimpleLayout string (including the level of logging information and information),

Org, apache log4j. TTCCLayout (contains the logs generated time, thread, categories, etc.)

Log4J USES the print format similar to the printf function in C language to format the log information. The print parameters are as follows:

% m  Output the message specified in the code

% p  The output priority is DEBUG, INFO, WARN, ERROR, FATAL

% r  Output the number of milliseconds since the application was started to output this log information

% c  The class to which the output belongs is usually the full name of the class

% t  Output the name of the thread that produced the log event

% n  Output a carriage return newline character, Windows platform is "rn", Unix platform is "n"

% d  The date or time of the output log time point is ISO8601 by default or can be specified later, for example: %d{yyy  MMM  Dd  HH:mm:ss,SSS}, output similar: October 18, 2002   22:10:28, 921

% l  Output the location where the log event occurred, including the class name, the thread that occurred, and the number of lines in the code. Example: Testlog4. Main (10) Testlog4. Java:

X: %   Output the NDC(nested diagnostic environment) associated with the current thread, especially as java ; Servlets such as multi-client multi-threaded applications.

% % :   Output a "%" character %F:& PI; The name of the file in which the output log message is generated

% L:   Output the line number in the code

M: %   Output the message specified in the code to produce the log details

% n:   Output a carriage return newline, "\r\n" for Windows and "\n" for Unix. Log newline can be modified between % and pattern characters to control their minimum width, maximum width, and text alignment.

Such as:

1)%20c: specify the name of the output category. The minimum width is 20. If the category name is less than 20, it is right-aligned by default.

2)%-20c: specify the name of the output category, with a minimum width of 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 name of the category is greater than 30, the extra characters on the left will be truncated, but there will be no Spaces if the name is less than 30.

C: if the name of the category is less than 20, fill in the space and align it to the right. If the name is longer than 30 characters, cut off the exported characters from the left.

How log4j.xml is configured


View Code 
<?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"
        class="org.apache.log4j.RollingFileAppender">
        <param name="File" value="logfile08.html" />
        <param name="MaxFileSize" value="1MB" />
        <param name="MaxBackupIndex" value="5" />
        <layout class="org.apache.log4j.HTMLLayout">
        </layout>
    </appender>
    <root>
        <level value="debug" />
        <appender-ref ref="appender1" />
    </root>
</log4j:configuration>

Log4j is used in the code

Before using Log4j in your program, import the commons-logging.jar and logging-log4j.1.2.9.jar into your classpath and place log4j.properties in the SRC root. Using log4j in the class, you first declare a static variable   Logger  Logger = logger.getlog ("classname").

The usage is as follows: logger.debug(" debug&dispenses; The message ") or the logger. The info (" info  The message ").

1. Get the recorder  

With Log4j, the first step is to get the logger, which is responsible for controlling the log information.

Its syntax is:

Public  Static  Logger  GetLogger (  String  Name)

Gets the logger by the specified name and, if necessary, creates a new logger for that name. Name usually takes the Name of this class, such as:

Static  Logger  Logger  =   Logger. GetLogger  (  ServerWithLog4j. Class. GetName  (a)  )

 

2. Read the configuration file  

When the logger is obtained, the second step will configure the Log4j environment with the syntax:

BasicConfigurator. Configure  () :   Automatically and quickly use the default Log4j environment.

PropertyConfigurator. Configure  (  String  ConfigFilename)   : reads a configuration file written using a Java properties file.

DOMConfigurator. Configure  (  String  Filename )   : reads the configuration file in XML form.

 

3. Insert record information (formatted log information)  

When the last two necessary steps are completed, you can easily insert logging statements with different priority levels wherever you want to log, with the syntax:

Logger. Debug  (  Object  Message )  ;

Logger. Info  (  Object  Message )  ;

Logger. Warn  (  Object  Message )  ;

Logger. Error  (  Object  Message )  ;  

 

demo

1. Use the program to output log information


package org.demo.log4j.dennisit;

 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 Re years     <a href="mailto:DennisIT@163.com"> Send E-mail </a>
  *    
  *  @since       :  1.0         Creation time :    2013-1-1         In the afternoon 03:19:42
  *     
  *  @function :   Output the log by code 
  *
  */

 public class Log4jPrintByCode {

     private static Logger logger = Logger.getLogger(Log4jPrintByCode.class);

     private Layout layout = new SimpleLayout();
     private FileAppender fileAppender;

 
     //With construct dependencies, the object is initialized when created
     public Log4jPrintByCode(Layout layout, Level level,String distDir){

         BasicConfigurator.configure();        //Using the default configuration information, you do not 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 side

     }

     
     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;
     }

     

 }

To improve efficiency, we can add judgment before writing a journal:

//Log the debug level information
if (logger.isDebugEnabled()) {
    logger.debug("This is debug message from Dao.");
}
//Record info level information
if (logger.isInfoEnabled()) {
    logger.info("This is info message from Dao.");
}

If this class is used as a base class, such as BaseDao, BaseAction, BaseService, etc., in J2EE, we can classify the log information of each layer and output it to each file.

2.Log4J outputs the same log information to multiple destinations


 
create database db_log4j;

use  db_log4j;

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 ' The current thread ',
    level varchar(45) default null comment ' Current log level ' ,
    class varchar(45) default null comment ' The class that generates the log ',
    message varchar(245) default null comment ' Log details ',
    primary key(logId)
);

The application instance outputs log information to the console, file, and database simultaneously.

Create databases and tables


 
create database db_log4j;

use  db_log4j;

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 ' The current thread ',
    level varchar(45) default null comment ' Current log level ' ,
    class varchar(45) default null comment ' The class that generates the log ',
    message varchar(245) default null comment ' Log details ',
    primary key(logId)
);

The configuration file log4j.properties

# define 3 An output terminal 
log4j.rootCategory=INFO,A1,A2,A3
# define A1 Output to controller 
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# define A1 The layout pattern is PaternLayout
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
#  define A1 Output format 
log4j.appender.A1.layout.ConversionPattern=%4p [%t] (%F:%L) - %m%n
# define A2 Output to file 
log4j.appender.A2=org.apache.log4j.RollingFileAppender
# define A2 Which file is output to 
log4j.appender.A2.File=./log/sysLog.log
# define A2 The maximum length of the output file 
log4j.appender.A2.MaxFileSize = 1KB
# define A2 Number of backup files 
log4j.appender.A2.MaxBackupIndex = 3
# define A2 The layout pattern is PatternLayout
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
# define A2 Output mode 
log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm:ss}:%p %t %c - %m%n
# define A3 Output to 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 A3 The layout and execution of SQL statements 
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')

Java test code

package org.demo.log4j.dennisit;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
 *
 *  @version  :  1.1
 *  
 *  @author   :   Su Re years     <a href="mailto:DennisIT@163.com"> Send E-mail </a>
 *    
 *  @since       :  1.0         Creation time :    2013-1-1         In the afternoon 04:13:59
 *     
 *  @function :   Control log information output 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 files are stored in the configure folder in the same directory as SRC

        //If placed under SRC, the parameter should be "bin/log4j.properties" or "SRC /log4j.properties". It is recommended that bin prevail

        //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");
    }
}


Related articles: