Use LOG4J for project configuration log output application and sample Demo implementation Analysis _java

Source: Internet
Author: User
Tags html form print format syslog create database log4j

LOG4J Component Composition

The log4j is composed of three important components:

1. Priority of log information (Logger)

2. Output Destination of log information (Appender)

3. The output format of the log information (Layout).

Profile:

The priority of log information from high to low has error, WARN, INFO, DEBUG, respectively, 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 file;

The output format controls the display content of the log information.

log4j Introduction

Log4j is an open source project for Apache, by using log4j, we can control the destination of log information delivery is console, file, GUI component, even interface server, NT Event recorder, UNIX syslog daemon, etc. , we can also control the output format of each log, by defining the level of each log information, we can more carefully control the log generation process. log4j--Log for Java (Java logs).

log4j Download Address: http://logging.apache.org/log4j/2.x/download.html

Format of log4j configuration file

LOG4J supports two types of configuration file formats:

1. XML-formatted files

2. File in properties format

You can also configure the LOG4J environment in code without using a configuration file at all. However, using a configuration file will make your application more flexible.

log4j Define a configuration file

1. Configure Root Logger

Its syntax is:

Copy Code code as follows:

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

Parameter description:

Level is the priority of logging, divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or levels you define.

OFF: Highest level, used to close all log records

Fatal: Indicates that each critical error event will cause the application to exit.

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

Warn: Indicates a potential error condition

Info: Generally used at the coarse-grained level, emphasizing the full operation of the application

Debug: Generally and at a coarse-grained level, emphasize the full operation of the application.

All: lowest level, used to open all log records.

LOG4J recommends using only four levels, from high to low, respectively, for error, WARN, INFO, and DEBUG. By the level defined here, you can control the switch to log information at the appropriate level in your application.

Appendername refers to where the log information is exported and can specify multiple output destinations at the same time.

2. Configure log information output destination Appender

Its syntax is:

Copy Code code as follows:

Log4j.appender.appenderName = Fully.qualified.name.of.appender.class

Log4j.appender.appenderName.option1 = value1

...

Log4j.appender.appenderName.option = Valuen


LOG4J offers the following appender:

Org.apache.log4j.ConsoleAppender (console)

Org.apache.log4j.FileAppender (file)

Org.apache.log4j.DailyRollingFileAppender (Generate a log file every day)

Org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches a specified size)

Org.apache.log4j.WriterAppender (send log information to any specified place in streaming format)

3. Configure the format of log information

The syntax is:

Copy Code code as follows:

Log4j.appender.appenderName.layout = Fully.qualified.name.of.layout.class

Log4j.appender.appenderName.layout.option1 = value1 ...

Log4j.appender.appenderName.layout.option = Valuen


LOG4J offers the following layout:

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

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)

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{yyy 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. Example: Testlog4.main (testlog4.java:10)

%x: The NDC (nested diagnostics environment) associated with the current line threads relative, especially in multiple client multi-threaded applications such as Java Servlets.

Percent%: output a "%" character%F: The name of the file where the output log message was generated

%l: line number in output code

%M: The message specified in the output code, the resulting log specific information

%n: Output a carriage return line break, Windows platform "\ r \ n", Unix platform for "\ n" output log message wrapping can be used to control the minimum width, maximum width, and text alignment between% and pattern characters.

Such as:

1)%20c: Specifies the name of the output category, the minimum width is 20, and if the category name is less than 20, the default is right-aligned.

2)%-20c: Specifies the name of the output category, the minimum width is 20, if the category name is less than 20, the "-" number specifies left-aligned.

3)%.30c: Specifies the name of the output category, the maximum width is 30, if the category name is greater than 30, will be the left more characters truncated, but less than 30 words will not have spaces.

4)%20.30c: If the name of the category is less than 20 to fill the space, and the right alignment, if its name is longer than 30 characters, from the left side of the exported characters are cut off.

How Log4j.xml is configured

Copy Code code as follows:

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>


using log4j in code

Before you use log4j in your program, you first import Commons-logging.jar and Logging-log4j-1.2.9.jar into classpath and place log4j.properties in the src root directory. Using log4j in a class, you first declare a static variable Logger logger=logger.getlog ("classname"). You can use it now.

The usage is as follows: Logger.debug ("debug Message") or Logger.info ("info message").

1. Get the Recorder

Using log4j, the first step is to get the logger, which will be responsible for controlling 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 generally takes the names of this class, such as:

  static Logger Logger = Logger.getlogger (ServerWithLog4j.class.getName ())

2. Read the configuration file

When the logger is obtained, the second step configures the LOG4J environment with the following syntax:

  Basicconfigurator.configure (): Automatically and quickly uses the default log4j environment.

Propertyconfigurator.configure (String configfilename): Reads a configuration file written using a Java-specific attribute file.

Domconfigurator.configure (String filename): Reads a configuration file in XML form.

3. Insert record information (format log information)

When the two necessary steps have been completed, you can easily insert any of the different priority logging statements into the places you want to log, as follows:

Logger.debug (Object message);

Logger.info (Object message);

Logger.warn (Object message);

Logger.error (Object message);

Program Demo

1. Log information output using the program

Copy Code code as follows:

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: Sujonin <a href= "mailto:dennisit@163.com" > Send mail </a>
*
* @since: 1.0 Date Created: 2013-1-1 03:19:42
*
* @function: Log output through code
*
*/

public class Log4jprintbycode {

private static Logger Logger = Logger.getlogger (Log4jprintbycode.class);

Private Layout Layout = new Simplelayout ();
Private Fileappender Fileappender;


Class using construction dependencies when creating an object.
Public Log4jprintbycode (Layout Layout, Level level,string Distdir) {

Basicconfigurator.configure (); Use default configuration information, 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 log output level
Fileappender = new Fileappender (layout,distdir,false);
Logger.addappender (Fileappender); To add an output port

}


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 increase our judgment before writing a log:
Copy Code code as follows:

Logging the debug level information
if (logger.isdebugenabled ()) {
Logger.debug ("This are debug message from Dao.");
}

Log information at info level
if (logger.isinfoenabled ()) {
Logger.info (' This is info ' from Dao. ');
}


If this class is a base class, such as Basedao, Baseaction, Baseservice, and so on in Java EE, then we can export the log information of each layer to each file.

2.log4j output the same log information to multiple destinations

Copy Code code as follows:

/* CREATE DATABASE/*
Create Database db_log4j;

/* Switch Database * *
Use db_log4j;

/* Log Information Form * *
CREATE TABLE Tb_log (
Logid int NOT null auto_increment comment ' serial number ',
CreateDate varchar () default NULL comment ' Log generation time ',
Thread varchar () default NULL comment ' current thread ',
Level varchar () default NULL comment ' current log levels ',
Class varchar () default NULL comment ' Generate log classes ',
Message varchar (245) default NULL comment ' Log specific information ',
Primary KEY (Logid)
);

The application instance outputs the log information to the console, files, and databases at the same time.

Creating databases and Tables

Copy Code code as follows:

/* CREATE DATABASE/*
Create Database db_log4j;

/* Switch Database * *
Use db_log4j;

/* Log Information Form * *
CREATE TABLE Tb_log (
Logid int NOT null auto_increment comment ' serial number ',
CreateDate varchar () default NULL comment ' Log generation time ',
Thread varchar () default NULL comment ' current thread ',
Level varchar () default NULL comment ' current log levels ',
Class varchar () default NULL comment ' Generate log classes ',
Message varchar (245) default NULL comment ' Log specific information ',
Primary KEY (Logid)
);


Configuration file Log4j.properties
Copy Code code as follows:

#定义3个输出端
Log4j.rootcategory=info,a1,a2,a3

#定义A1输出到控制器
Log4j.appender.a1=org.apache.log4j.consoleappender
#定义A1的布局模式为PaternLayout
Log4j.appender.a1.layout=org.apache.log4j.patternlayout
# defines the output format of the A1
log4j.appender.a1.layout.conversionpattern=%4p [%t] (%f:%l)-%m%n

#定义A2输出到文件
Log4j.appender.a2=org.apache.log4j.rollingfileappender
#定义A2输出到哪个文件
Log4j.appender.a2.file=./log/syslog.log
#定义A2输出文件的最大长度
Log4j.appender.A2.MaxFileSize = 1KB
#定义A2的备份文件数
Log4j.appender.A2.MaxBackupIndex = 3
#定义A2的布局模式为PatternLayout
Log4j.appender.a2.layout=org.apache.log4j.patternlayout
#定义A2的输出模式
LOG4J.APPENDER.A2.LAYOUT.CONVERSIONPATTERN=%D{YYYY-MM-DD hh:mm:ss}:%p%t%c-%m%n

#定义A3输出到数据库
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
#定义A3的布局和执行的SQL语句
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
Copy Code code as follows:

Package org.demo.log4j.dennisit;

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

/**
*
* @version: 1.1
*
* @author: Sujonin <a href= "mailto:dennisit@163.com" > Send mail </a>
*
* @since: 1.0 Date Created: 2013-1-1 04:13:59
*
* @function: Output to multiple destination via profile control log information
*
*/

public class Log4jprintbyconfigure {

private static Logger Logger = Logger.getlogger (Log4jprintbyconfigure.class);

public static void Main (string[] args) throws Exception {

Load Log configuration file Log4j.properties
Propertyconfigurator.configure ("configure/log4j.properties")//file is stored in the Configure folder of SRC and directory

If placed under SRC, the parameter should be "Bin/log4j.properties" or "src/log4j.properties", the recommended bin as the standard

The following information will be printed and exported
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 are fatal message");
}

}

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.