Methods of using log4j and slf4j for log output in Java

Source: Internet
Author: User
Tags log log java web log4j

The output log in Java is commonly used in log4j, where the log4j configuration and usage are described, as well as the use of slf4j.

First, download Log4j's rack package, and import the project, as follows:

Ii. Creating a log4j.properties configuration file

1. Location of log4j configuration file:

(1) In the case of a Java Project project, create the log4j.properties in the root directory of the project instead of the SRC directory.

(2) In the case of a Java Web project, create the Log4j.properties configuration file in the SRC directory, because this time Tomcat will go to the default load of this configuration file, without the need for us to manually load the log4j configuration file.

Log4j.properties configuration content is as follows:

1 log4j.rootlogger=info,logtest 2 Log4j.appender.logtest=org.apache.log4j.dailyrollingfileappender 3 Log4j.appender.logtest.file=/logs/logtest/logtest.log 4 log4j.appender.logtest.datepattern= '. ' Yyyy-mm-dd '. Log '5log4j.appender.logtest.layout=org.apache.log4j.patternlayout6 Log4j.appender.logtest.layout.conversionpattern=[logtestinfo] [%d][%c][%-5p]%m%n

2. Description of log4j configuration item:

(1) The first line in the Rootlogger configuration is the entire project log output, you can also only for a certain module for the log output, such as the first line configured to Log4j.logger.com.logtest.project=info,logtest, The log is only output under Project path Com/logtest/project.

Info is a log level and can be divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all. Configure as info to show only the log information for info, WARN, and error.

Logtest the name of the log configuration, the corresponding detailed configuration is below.

(2) The second line specifies the type of log output.

The optional parameters are as follows:

Org.apache.log4j.ConsoleAppender (console)

Org.apache.log4j.FileAppender (file)

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

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

Org.apache.log4j.WriterAppender (send log information in stream format to any specified location)

(3) The third line is the path and file name of the specified log file output.

1) If output to the specified location: Log4j.appender.logtest.file=d:\\logtest.log

2) If the output is in the current Tomcat working directory: Log4j.appender.logtest.file=${catalina.home}/logtest/logtest.log

(4) The fourth line is set with the second row, the time interval generated by the log format settings, formatted text will be used as the suffix of the log file.

Take the fourth line above as an example, generating a new logTest.log log file every day, and naming the log of the previous days as Logtest.log.2017-07-07.log. Note: Text that is not processed in Datepattern is placed in single quotation marks ('), such as (.) and (. log).

The optional parameters are as follows:

1) '. ' YYYY-MM: Monthly

2) '. ' YYYY-WW: Weekly

3) '. ' YYYY-MM-DD: Every day

4) '. ' Yyyy-mm-dd-a: Every half day

5) '. ' YYYY-MM-DD-HH: Per hour

6) '. ' YYYY-MM-DD-HH-MM: Per minute

(5) The fifth line is the format of the specified log output.

The optional parameters are as follows:

1) org.apache.log4j.HTMLLayout (layout in HTML table format)

2) Org.apache.log4j.PatternLayout (flexibility to specify layout mode)

3) Org.apache.log4j.SimpleLayout (contains the level of log information and information string)

4) Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, etc.) of the log generation

(6) Line Six is formatted with the fifth line setting to format the log output.

With the sixth line set as an example, [logtestinfo] [%d][%c][%-5p]%m%n output is:

The formatting parameters are described as follows:

%M the message specified in the output code.

%p output priority, or debug,info,warn,error,fatal.

The%r output is the number of milliseconds that the log information is consumed from the application boot to output.

The class that the%c output belongs to, usually the full name of the class in which it is located.

The%t output the name of the thread that generated the log event.

%n outputs a carriage return newline character, the Windows platform is "RN", and the UNIX platform is "n".

%d the date or time of the output log time, the default format is ISO8601, or the format can be specified later, for example:%d{yyyy MM DD hh:mm:ss,sss}.

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

Percent: Outputs a "%" character.

%F: The name of the file where the output log message was generated.

%l: The line number in the output code.

You can add modifiers between% and pattern characters to control their minimum width, maximum width, and text alignment. Such as:

1)%20c: Specifies the output class destination name, the minimum width is 20, if the class destination name is less than 20, the default is the case of right alignment.

2)%-20c: Specifies the output class destination name, the minimum width is 20, if the class destination name is less than 20, the "-" number specifies left-justified.

3)%.30c: Specifies the output class destination name, the maximum width is 30, if the class destination name is greater than 30, will be the left more than the character of the cut off, but less than 30, there will be no spaces.

4)%20.30c: If the class destination name is less than 20, fill the space, and right-aligned, if its name is longer than 30 characters, it will be truncated from the more distant characters on the left.

Three, the log output code example

(1) Create a Logger object in the class.

1 Private Logger Logger = Logger.getlogger (this. getclass ());

(2) Use logger to output logs.

1 logger.info ("TestInfo 1");

Output effect:

Here, the configuration and use of log4j is finished. Below by the way the use of slf4j.

Iv. use of slf4j with log4j

SLF4J: Simple log façade (easy Logging facade for Java), not a specific log solution, it only serves a wide variety of log systems. Officially, SLF4J is a simple facade for the log system, allowing end users to use the log system they want when they deploy their apps.

When using SLF4J, you do not need to specify in the code or the configuration file that you intend to use the specific log system, SLF4J provides a unified logging interface, as long as the method provided by the record can be, the final log format, record level, output mode, etc. through the configuration of the specific log system to achieve, Therefore, it is possible to switch the log system flexibly in the application.

(1) Download the SLF4J rack package and import the project as follows:

(2) directly using the above 2nd log4j configuration can be, without additional configuration slf4j.

(3) Create the Logger object in the class.

1 Private Logger Logger = Loggerfactory.getlogger (this. getclass ());

Note here to use the logger in the SLF4J rack package instead of the logger in the log4j rack package.

(3) Use logger to output logs.

1 logger.info ("TestInfo 1"); 2 logger.info ("TestInfo {}", "1");

SLF4J has two output modes, in addition to splicing string output like log4j, but also provides a parameterized way of output, that is, the second line above the way, with a pair of curly braces to represent the parameter bit, the following 1 is the value of the argument.

Methods of using log4j and slf4j for log output in Java

Related Article

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.