The use and configuration of Java Log Framework slf4j and log4j

Source: Internet
Author: User

Logging naturally is very important, but I am afraid to remember slf4j and log4j, such as the configuration of the log framework is very few people, this thing is not difficult, but only after the configuration is rarely to move it, the development of new projects are usually copied from other projects, or reference to the document

Needless to say, say log4j first, use log4j as simple as a few steps

First, get the log4j jar package, the MAVEN project configures the following dependencies on the line, or download the jar package from Ali's Maven repository and add it to the project's "Build Path"

<dependency><groupid>log4j</groupid><artifactid>log4j</artifactid><version >1.2.17</version></dependency>

Then, the whole log4j.properties, the contents of the following as an example, do not understand it does not matter, the following will detail this thing, which is the focus of the log4j configuration

log4j.rootlogger=info,consolelog4j.additivity.org.apache=true#consolelog4j.appender.console= Org.apache.log4j.consoleappenderlog4j.appender.console.threshold=infolog4j.appender.console.immediateflush= truelog4j.appender.console.target=system.outlog4j.appender.console.layout= Org.apache.log4j.patternlayoutlog4j.appender.console.layout.conversionpattern=%d{yyyy-mm-dd HH:MM:SS} [%p]%m%n

Finally, in your code, use the

Package Com.xmyself.log4j;import Org.apache.log4j.logger;public class Main {public static void main (string[] args) {new T EST (). Test ();}} Class Test {final Logger log = Logger.getlogger (test.class);p ublic void Test () {log.info ("Hello this is log4j info log");} }

Run the main method and the log information is out.

2016-12-01 21:23:29 [INFO] Hello this is log4j info log

The question also comes, where can log4j.properties be put to be resolved?

First, configure the log4j.properties path

Parsing log4j.properties Specific content is certainly the log4j of the class in the jar package, as to which class I do not study, that log4j.properties where to put and how to configure to be resolved? Different project types are configured differently

1. Common Java Engineering or spring engineering

This is the most common type of Java project, write demo with more, put Log4j.properties in the Src/main/java directory (that is, the root directory of the package)

Run the main method to see the log, and finally the whole of a complete log4j demo!

2. Spring MVC Project

The Web project is built with spring MVC, placing log4j.properties in the Src/main/resources conf directory (Web engineering configuration files are usually in the resources or Web-inf directory), Edit Web. Xml to add

<context-param><param-name>log4jconfiglocation</param-name><param-value>classpath:/ Conf/log4j.properties</param-value></context-param><listener><listener-class> Org.springframework.web.util.log4jconfiglistener</listener-class></listener>
3. General Web Engineering

Without the listener load log4j.properties provided by spring, how do we load this file? Similarly, put log4j.properties in the Conf directory of src/main/resources, we complete a servlet to load

public class Log4jservlet extends HttpServlet {    private static final long serialversionuid = 1L;     public void init (ServletConfig config) throws servletexception {        String prefix = This.getclass (). getClassLoader (). GetResource ("/"). GetPath ();        String Path = Config.getinitparameter ("Log4j-path");        Propertyconfigurator.configure (prefix + path);    }    public void Doget (HttpServletRequest req, httpservletresponse Res) throws IOException, servletexception {} public    void DoPost (HttpServletRequest req, httpservletresponse Res) throws IOException, servletexception {} public    void Destroy () {}}

Then configure the servlet to initialize as the Web project is started, edit the website. XML, add

<servlet><servlet-name>log4j</servlet-name><servlet-class> com.xmyself.log4j.log4jservlet</servlet-class><init-param><param-name>log4j-path</ param-name><param-value>conf/log4j.properties</param-value></init-param>< Load-on-startup>1</load-on-startup></servlet>

It looks like spring mvc, and even you think about it, the normal Java project does not specify the path of log4j.properties, which means that the log4j jar package must have a default path. In addition, it is recommended that the configuration of the log4j be placed first, since the subsequent loading of other components will start using logging

Now, you can be in many types of Java project log, but are the console of the log, the output is very limited, the following we will detail how to configure the Log4j.properties content

Second, the configuration log4j.properties content

The next introduction of the content looks independent, in fact interrelated, and very regular, we want to output the log, the first to have a log object (logger), then these log objects to the log output to where, the console or file, it is necessary to set the output location (Appender), The format and content of the output is what kind of, it is necessary to set the output style (layout), these settings are finished, log4j configuration is finished

1. Log level

log4j logs are divided into 7 levels: all, DEBUG, INFO, WARN, ERROR, FATAL, OFF, however, it is recommended to use only "DEBUG" to "ERROR" four levels, from "All" to "OFF" level from low to high, it is important to understand that Since the output log level is set, only logs with a rank equal to or higher than this level will be output, for example, the output log level is set to "INFO" and the "DEBUG" level of the log will not be output

2, Logger

The log instance is the Logger object instantiated in the code.

Log4j.rootlogger=level,appendername1,appendername2,... Log4j.additivity.org.apache=false: Indicates that it will not output in the appender of the parent logger, by default true

This is the global logger configuration, level is used to set the log rank, appendername define the log output, the example "console" is a log output

Here is a clearer example of configuring logger objects instantiated in all classes under the "Com.demo.test" package

Log4j.logger.com.demo.test=debug,testlog4j.additivity.com.demo.test=false
3, Appender

Log output, specifying the output location of the logger

Log4j.appender.appendername=classname

Appender has 5 options

Org.apache.log4j.ConsoleAppender (console) org.apache.log4j.FileAppender (file) org.apache.log4j.DailyRollingFileAppender (generates a log text per day Org.apache.log4j.RollingFileAppender (creates a new file when the file size reaches the specified size) Org.apache.log4j.WriterAppender (sends the log information in stream format to any specified location)

Each appender has several configuration items, each of which is described below

Consoleappender (Common)

Threshold=warn: Specifies the lowest output level of the log information, default debugimmediateflush=true: Indicates that all messages will be output immediately, set to False to not output, the default value is truetarget= System.err: The default value is System.out

Fileappender

Threshold=warn: Specifies the lowest output level of log information, default debugimmediateflush=true: Indicates that all messages will be output immediately, set to False to not output, default trueappend= False:true indicates that the message was added to the specified file, false to overwrite the specified file content, default truefile=d:/logs/logging.log4j: Specify message output to logging.log4j file

Dailyrollingfileappender (Common)

Threshold=warn: Specifies the lowest output level of log information, default debugimmediateflush=true: Indicates that all messages will be output immediately, set to False to not output, default trueappend= False:true indicates that the message was added to the specified file, false to overwrite the specified file content, and default truefile=d:/logs/logging.log4j: Specifies that the current message is output to the logging.log4j file Datepattern = '. ' YYYY-MM: Scrolls the log file once a month, resulting in a new log file per month. The log file name for the current month is logging.log4j, the first one months of the log file is logging.log4j.yyyy-mm In addition, you can also specify by week, day, time, minutes, etc. to scroll the log file, corresponding to the following format: 1) '. ' YYYY-MM: 2 per month) '. ' YYYY-WW: 3 per week) '. ' YYYY-MM-DD: 4 per day) '. ' Yyyy-mm-dd-a: Two times a day 5) '. ' YYYY-MM-DD-HH: 6 per hour) '. ' YYYY-MM-DD-HH-MM: Per minute

Rollingfileappender

Threshold=warn: Specifies the lowest output level of log information, default debugimmediateflush=true: Indicates that all messages will be output immediately, set to False to not output, default trueappend= False:true indicates that the message was added to the specified file, false to overwrite the specified file content, and default truefile=d:/logs/logging.log4j: Specifies that the message is output to the logging.log4j file maxfilesize= 100KB: suffix can be kb,mb or GB. When the log file reaches this size, it scrolls automatically, moving the original content to the Logging.log4j.1 file maxbackupindex=2: Specifies the maximum number of scrolling files that can be produced, for example, Set to 2 to generate logging.log4j.1,logging.log4j.2 two scrolling files and one logging.log4j file
4. Layout

Specify logger output content and format

Log4j.appender.appendername.layout=classname

Layout has 4 options

Org.apache.log4j.HTMLLayout (layout as HTML table) Org.apache.log4j.PatternLayout (flexibility to specify layout mode) Org.apache.log4j.SimpleLayout (level with log information and information Strings) Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, etc.) of the log

Layout also has configuration items, the following details

Htmllayout

Locationinfo=true: Output Java file name and line number, default Falsetitle=my Logging: Default value is log4j Log Messages

Patternlayout (most commonly used configuration)

conversionpattern=%m%n: Sets the format in which messages are displayed

The parameters for formatting are described below

%p: The priority of the output log information, that is, debug,info,warn,error,fatal%d: the date or time of the output log point in time, the default format is ISO8601, or the format can be specified later, such as:%d{yyyy/mm/dd hh:mm:ss,sss }%r: Output from application startup to output this log information is consumed in milliseconds%t: Output the thread name that generated the log event%l: The location of the output log event, equivalent to the combination of%c.%m (%f:%l), including the class name, method, file name, and number of rows in the code% C: Output log information belongs to the class, usually is the class name%m: Output The method name of the log information%f: Output log message is generated when the file name%l: The line number in the output code%m: The specific log information specified in the output code%n: output a carriage return line break, the Windows platform is "RN", The UNIX platform is "n"%x: the NDC (nested diagnostic environment) associated with the current line threads, especially for multi-client multithreaded applications like Java Servlets: Outputs a "%" character # # # #另外, and can also be used to control its minimum length by adding modifiers between% and format characters , the maximum length, and the alignment of the text. such as: 1) C: Specify the name of the output category, the minimum length is 20, if the category name length is less than 20, the default is the right alignment 2)%-20c: "-" number for left-justified 3)%.30c: Specifies the name of the output category, The maximum length is 30, if the category name length is greater than 30, will be the left more than the character of the cut off, but less than 30 will not fill the space
5. Complete Example

After the configuration, we started to configure, first to get a few log output

Log4j.rootlogger=debug,console,dailyfile,rollingfile,logfilelog4j.additivity.org.apache=true

Then a configuration of one

Console console Log output

# Console (consoles) log4j.appender.console=org.apache.log4j.consoleappenderlog4j.appender.console.threshold= debuglog4j.appender.console.immediateflush=truelog4j.appender.console.target= system.errlog4j.appender.console.layout= Org.apache.log4j.patternlayoutlog4j.appender.console.layout.conversionpattern=%d{yyyy-mm-dd HH:MM:SS} [%p]%m%n

File logfile Log renderer

# log file (logFile) log4j.appender.logfile=org.apache.log4j.fileappenderlog4j.appender.logfile.threshold= Debuglog4j.appender.logfile.immediateflush=truelog4j.appender.logfile.append=truelog4j.appender.logfile.file=d :/logs/log.log4jlog4j.appender.logfile.layout= Org.apache.log4j.patternlayoutlog4j.appender.logfile.layout.conversionpattern=%d{yyyy-mm-dd HH:MM:SS} [%p]%m%n

Scrolling file Rollingfile log output

# scrolling file (rollingfile) log4j.appender.rollingfile= Org.apache.log4j.rollingfileappenderlog4j.appender.rollingfile.threshold= Debuglog4j.appender.rollingfile.immediateflush=truelog4j.appender.rollingfile.append= Truelog4j.appender.rollingfile.file=d:/logs/log.log4jlog4j.appender.rollingfile.maxfilesize= 200kblog4j.appender.rollingfile.maxbackupindex=50log4j.appender.rollingfile.layout= Org.apache.log4j.patternlayoutlog4j.appender.rollingfile.layout.conversionpattern=%d{yyyy-mm-dd HH:MM:SS} [%p]%m %n

Periodic scrolling of files Dailyfile log output

# Periodic scrolling log file (dailyfile) log4j.appender.dailyfile= Org.apache.log4j.dailyrollingfileappenderlog4j.appender.dailyfile.threshold= Debuglog4j.appender.dailyfile.immediateflush=truelog4j.appender.dailyfile.append= Truelog4j.appender.dailyfile.file=d:/logs/log.log4jlog4j.appender.dailyfile.datepattern= '. ' yyyy-mm-ddlog4j.appender.dailyfile.layout= Org.apache.log4j.patternlayoutlog4j.appender.dailyfile.layout.conversionpattern=%d{yyyy-mm-dd HH:MM:SS} [%p]%m%n
6. Local Log

The log configuration of the above method is global, all code uses the same set of log configuration, the actual project is not so, the project running log, database access log and so on usually do not output to the same file.

How to let different packages, classes output different logs, even the same class output a different log? The answer is to specify a separate log output for them

Log4j.logger.com.demo.test=debug,testlog4j.appender.test=org.apache.log4j.fileappenderlog4j.appender.test.file =/log/test.loglog4j.appender.test.layout= Org.apache.log4j.patternlayoutlog4j.appender.test.layout.conversionpattern=%d{yyyy-mm-dd HH:MM:SS} [%p]%m%n

Specify the log output "test" for the "Com.demo.test" package

You can also have the same class output a different log

private static Log Logger1 = Logfactory.getlog ("MyTest1");p rivate static Log logger2 = Logfactory.getlog ("MyTest2");

You need to create two logger in this class, and then configure each

log4j.logger.mytest1= debug,test1log4j.additivity.mytest1=falselog4j.appender.test1= org.apache.log4j.fileappenderlog4j.appender.test1.file=/log/test1.loglog4j.appender.test1.layout= Org.apache.log4j.patternlayoutlog4j.appender.test1.layout.conversionpattern=%d{yyyy-mm-dd HH:MM:SS} [%p]%m%n log4j.logger.mytest2=debug,test2log4j.appender.test2=org.apache.log4j.fileappenderlog4j.appender.test2.file=/ log/test2.loglog4j.appender.test2.layout= Org.apache.log4j.patternlayoutlog4j.appender.test2.layout.conversionpattern=%d{yyyy-mm-dd HH:MM:SS} [%p]%m%n
Third, slf4j and log4j

What is SLF4J? SLF4J just defines a set of log interfaces, but does not provide any implementations, so why use SLF4J? Log4j not already met the requirements?

Yes, log4j meet the requirements, but, the log framework is not only log4j one, you like to use log4j, some people may prefer logback, some people even use the JDK's own log framework, in this case, if you want to rely on other people's jar, the entire system uses two log framework, If you rely on 10 jar, each jar with a different log framework, it is not a project with 10 log frame, it is messy!

If your code uses SLF4J interface, the specific log implementation framework you like to use log4j, other people's code is also used SLF4J interface, the specific implementation of the unknown, then you rely on other people jar package, the entire project will only use the LOG4J log framework, which is a typical façade pattern application, As with the JVM, we write the log code for SLF4J, SLF4J to handle the differences between the specific log implementation frameworks, as we write Java code for the JVM, and the JVM handles the differences between the operating systems, and the result is that it is written and run everywhere. Besides, more and more open source tools are now using SLF4J.

So, how do you use SLF4J?

First, get the SLF4J jar package, MAVEN relies on the following, log4j configuration process is completely unchanged

<dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId>< Version>1.7.21</version></dependency>

Then, get slf4j and log4j the associated jar package, through this thing, the call to the SLF4J interface into a call to log4j, different log implementation framework, this conversion tool is different

<dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version></dependency>

Finally, the code declares logger to change, the original use of log4j is this

Import Org.apache.log4j.logger;class Test {final Logger log = Logger.getlogger (test.class);p ublic void Test () {Log.info ( "Hello this is log4j info log");}}

Now it's going to change.

Import Org.slf4j.logger;import org.slf4j.loggerfactory;class Test {Logger log = Loggerfactory.getlogger (Test.class); public void Test () {log.info ("Hello, my name is {}", "Chengyi");}}

Found different, dependent logger changed, and, SLF4J API can also use placeholder, very convenient, in addition, all the same!

The use and configuration of Java Log Framework slf4j and log4j

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.