Home> Java> javaTutorial> body text

Introduction to the basic usage of Log4j

零下一度
Release: 2017-06-28 14:40:11
Original
1936 people have browsed it

Simple configuration

#指定logger # 配置Logger组件 # 设定Log4j的日志级别(error warn info debug) # 输出目的地(Console, logfile是appender的名字,是自己定义的,后面才赋予具体的含义) log4j.rootLogger=debug, Console, logfile ################################################################################################################### #指定appender(目的地) #设定Logger的Console(appender的名字)的Appender类型为控制台输出 #org.apache.log4j.ConsoleAppender 表明 Console是控制台输出 log4j.appender.Console=org.apache.log4j.ConsoleAppender #输出的格式 #设定Console的Appender布局Layout #org.apache.log4j.PatternLayout(可以灵活地指定布局模式)包含选项: # ConversionPattern=%m%n :指定怎样格式化指定的消息 log4j.appender.Console.layout=org.apache.log4j.PatternLayout #2009-09-29 07:30:43,265 INFO com.itcast.web.controller.SearchCdServlet.doGet() - e log4j.appender.Console.layout.ConversionPattern=%d %p %c.%M() - %m%n ################################################################################################################### #设定Logger的logfile(appender的名字)的Appender类型为文件大小到达指定尺寸的时候产生一个新的文件 log4j.appender.logfile=org.apache.log4j.RollingFileAppender #设定文件的输出路径(指定文件的名字和路径,tomcat的启动路径) log4j.appender.logfile.File=../logs/logstrore.log #设定后缀可以是KB, MB 或者是 GB. 在日志文件到达该大小时,将会自动滚动,即将原来的内容移到logstrore.log.1文件 log4j.appender.logfile.MaxFileSize=2048KB #Keep three backup files.指定可以产生的滚动文件的最大数 log4j.appender.logfile.MaxBackupIndex=4#设定logfile的Appender布局Layout log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%d %p %c.%M() - %m%n ###################################################################################################################
Copy after login

Log4JIntroduction

Log4J is an open source project of Apache. It is a log operation package. By using Log4J, you can specify the destination for log information output, such as console, file, CUI component, and NT event recorder. ;You can also control the output format of each log. In addition, by defining the level of log information, the output of the log can be controlled in great detail. The most interesting thing is that these functions can be flexibly configured through a configuration file without modifying the application code.

Outputting logs in the application has three purposes:

l Monitor changes in variables in the code, and periodically record the data to files for statistical analysis by other applications

l Track the code runtime trajectory as a basis for future audits

l Act as a debugger in the integrated development environment, printing code debugging information to files and consoles

Requirements The most common way to output logs in a program is to embed statements in the code. These print statements can output logs to the console or files. A better way is to construct a log operation class to encapsulate such operations instead of letting A series of print statements fills the body of the code.

Today, with the emphasis on reusable components, in addition to developing a reusable log operation class name from beginning to end, Apache provides us with a powerful Ready-made log operation package Log4J.

Log4J is mainly composed of three major components:

l Logger: Responsible for generating logs and being able to classify and filter log information. In layman’s terms, it is to decide what log information should be output and what log information should be output. Should be ignored

l Appender: Defines the destination for log information output and specifies where the log information should be output. These places can be consoles, files, network devices, etc.

l Layout: Specify the output format of log information

These three components work together to enable developers to record information according to log information categories, and to control the output format of log information and the log storage location during program running.

A Logger can have multiple Appenders, which means that log information can be output to multiple devices at the same time. Each Appender corresponds to a Layout, and Layout determines the format of the output log information.

Assume that according to actual needs, the log information in the program is required to be output to the console where the program is running, and to a specified file, and when the log information is output to the console, SimplLayout layout, when PatternLayout layout when log information is output to a file. At this time, the relationship between the three components of Logger, Appender and Layout is as shown in the figure

Appender component (specify output purpose)
The Appender component of Log4J determines where to output the log information. Recently, Log4J's Appender supports outputting log information to the following purposes:

lConsole(Console)

lFile

lGUI component

A logger can correspond to multiple Appenders at the same time, that is to say, the log information of a Logger can be output to multiple destinations at the same time, for example: to configure the rootLogger Two Appenders; one is file and the other is console, you can use the following configuration code:

LayoutComponent
Layout component is used to determine the output format of the log. It has the following types

l org.apache.log4j.HTMLLayout (Layout in HTML table format)

l org.apache.log4j.PatternLayout (the layout mode can be flexibly specified)

l org.apache.log4j.SimpleLayout (contains log information level and information String)

l org.apache.log4j.TTCCLayout (contains log generation time, thread and category information)

Log4j Basic usage method

To use Log4J in an application, first configure each component of Log4j in a configuration file, and then you can operate the log through the Log4JAPI in the program

Define configuration file
Log4J consists of three important components: Logger, Appender and layout. Log4J supports setting these components programmatically in the program, and also supports configuring components through configuration files. The latter method is more flexible.

Log4J supports two configuration file formats, one is XML format and the other is Java properties file,


1.Configure Logger component
The syntax is:
log4j.rootLogger = [ level ] , appenderName1, appenderName2, …

Example:

log4j.rootLogger =WARN,file,console


Level: is the priority of logging, divided into OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL or the level you define.

Log4j recommends using only four levels. The priorities from high to low are ERROR>WARN>INFO>DEBUG. Through the levels defined here, you can control the on and off of the corresponding level of log information in the application. For example, book it here If the INFO level is defined, all DEBUG level log information in the application will not be printed.

appenderName: specifies where the log information is output. You can specify multiple output destinations at the same time.

All: Print all logs.

Off: Close all logs.
For example: log4j.rootLogger=info,A1,B2,C3

2.ConfigurationAppenderComponent

The syntax is:
log4j.appender.appenderName =fully.qualified.name.of.appender.class.

Example:

log4j.appender.console=org.apache.log4j .ConsoleAppender


"fully.qualified.name.of.appender.class"
You can specify one of the following five destinations:
2.org.apache.log4j.FileAppender(File)[The log can only be output to one file, not recommended]
3.org.apache.log4j.DailyRollingFileAppender(generates a log file every day)## 4.org.apache.log4j.RollingFileAppender
(Generate a new file when the file size reaches the specified size)5.org.apache.log4j.WriterAppender
(Send log information to any specified place in streaming format)
A.ConsoleAppender

Threshold=WARN: Specifies the lowest level of log message output.ImmediateFlush=true: The default value is true, which means that all messages will be output immediately.

B.FileAppenderOption

Threshold=WARN: Specifies the lowest level of log message output.

ImmediateFlush=true: The default value is true, which means that all messages will be output immediately.

File=mylog.txt: Specify the message output to the mylog.txt file.
Append=false: The default value is true, which means that the message will be added to the specified file, false means that the message will overwrite the content of the file specified by

.
C.DailyRollingFileAppenderOptions
## Threshold=WARN: Specifies the lowest level of log message output.
ImmediateFlush=true: The default value is true, which means that all messages will be output immediately.
File=mylog.txt: Specify the message to be output to the mylog.txt file.
Append=false: The default value is true, which means that the message will be added to the specified file. False means that the message will overwrite the content of the specified

DatePattern='.'yyyy-ww: Roll the file once a week, that is, generate a new file every week. Of course, you can also

1)'.'yyyy-MM: Monthly
2)'.'yyyy-ww: Weekly
3)'.'yyyy-MM-dd: Every day
4)'.'yyyy-MM-dd-a: twice a day
5)'.'yyyy-MM-dd-HH: per hour
6)'.'yyyy-MM-dd-HH-mm: Every minute

D.RollingFileAppenderOption
Threshold=WARN: Specify The lowest level of log message output.
dle to to to to to to to to be to be very high to be true.
file = mylog.log: Specify the message output to the mylog.txt file.
Append=false: The default value is true, which means that the message will be added to the specified file, false means that the message will overwrite the content of the specified

MaxFileSize=100KB: The suffix can be KB, MB or GB. When the log file reaches the size

MaxBackupIndex=2: Specifies the maximum number of rolling files that can be generated.

3、Configure the format of log information


1)log4j .appender.appenderName.layout=fully.qualified.name.of.layout.class
"fully.qualified.name.of.layout.class"You can specify the following4One of the formats:

Example: log4j.appender.console.layout=org.apache.log4j.PatternLayout

log4j.appender.console.layout.ConversionPattern=%d %p %c.%M()-%m%n


LocationInfo=true: The default value is false, output java file name and line number


   2.org.apache.log4j.PatternLayout (which can flexibly specify layout patterns) contains options:

ConversionPattern=%m%n :Specify how to format the specified message.

    3.org.apache.log4j.SimpleLayout (contains the level and information string of log information)
    4.org.apache.log4j.TTCCLayout (including log generation time, thread, category and other information)
%-5p %d{yyyy-MM-dd HH:mm:ssS} %c %m%n
The meanings of several symbols in the log information format: -X number: X information is left aligned when output;%p: The priority of output log information, that is, DEBUG, INFO, WARN, ERROR, FATAL,
%d: The date or time of the output log time point, the default format is ISO8601, you can also specify the format afterwards, for example: %d{yyy MMM dd HH:mm:ss,SSS}, the output is similar: October 18, 2002 22: 10:28,921
%r: Output the number of milliseconds it took from the start of the application to the output of the log information
%c: The category to which the output log information belongs, usually the full name of the class
%t: Output the name of the thread that generated the log event
%l: Outputs the location where the log event occurred, equivalent to the combination of %C.%M (%F:%L), including the category name and the thread where it occurred, and the number of lines 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-threaded applications like java servlets.
%%: Output a "%" character
%F: Output the name of the file where the log message is generated
%L: Output the line number in the code
%m: Output the line number specified in the code Message, specific log information generated
%n: Output a carriage return and line feed, Windows platform is "\r\n", Unix platform is "\n" Output log information line feed

%M represents The name of the method


You can add modifiers between%and the pattern character to control its minimum width, maximum width, and text alignment. For example:## 1)%20c: Specify the name of the output category. The minimum width is 20, if the category name is less than 20.2)%-20c: Specify the name of the output category. The minimum width is 20. If the name of the category 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 name of the category is less than 20, fill in spaces and right-align. If the name is longer than 30 characters, truncate the characters from the left side.

To access Log4J in the program, you need to use the Log4J JAR file.
Using Log4J in the program includes the following processes:


l Read the configuration file and configure the Log4J environment

l Output the log information

Before entering into learning Log4J, we need to understand the two common interfaces LogFactory and Log in the general log package. Their usage is introduced below.

Log interface

The general log package divides log messages into 6 levels: FATAL (fatal), ERROR (error), WARN (warning), INFO (information), DEBUG (debugging) ) and TRACE (details). Among them, FATAL has the highest level and TRACE has the lowest level. The general log package uses a log level mechanism to flexibly control the output log content.

org.apache.commons.logging.Log interface represents the logger, which provides a set of methods for outputting logs:

l fatal(Object message): Output FATAL level log messages.

l error(Object message): Output ERROR level log messages.

l ……

l trace(Object message): Output TRACE level log messages.

For the above method of outputting logs, this method will be actually executed only when the level of the output log is greater than or equal to the log level configured for the log.For example, if the log level of the logger isWARN, then in the program, its fatal(), error()# The ## and warn()methods will be executed, but the info(), debug()and trace()methods will not Executed.

(二)LogFactoryInterface

Summary

OptionsTarget=System.err: By default: System.out, specify the output consolefile.specify months, weeks, days, hours and minutes. That is, the corresponding format is as follows:file., it will be automatically scrolled, that is, the original content will be moved to the mylog.log.1 file.The syntax is:## 1.org.apache.log4j.HTMLLayout (layout in HTML table format) includes options:Title=my app file: The default value is Log4J Log Messages.l Obtain the loggerThe Log interface also provides a set of methods to determine whether the output of log messages of a specific level is allowed:l isFatalEnabled()l isErrorEnabled()l ……l isTraceEnabled()Before the program outputs a log message of a certain level, it is recommended to call the above method to determine whether the log of this level is allowed to be output, which helps Improve application performance. For example, the following code first adds the log message to the StringBuffer, and finally calls the debug() method of the logger to output the log:StringBuffer buf = new StringBuffer();buf.append(" Login Successsul - ”);buf.append(“Name:”);buf.append(username);log.debug(buf.toString() );For the above code, if the logger actually does not allow the output of DEBUG level logs, then the debug() method of the logger will not output any messages, and a large string of messages will be added to the StringBuffer. All operations will be redundant. In order to improve performance, you can use the isDebugEnabled() method reasonably to avoid the application from performing redundant operations:if(log.isDebugEnabled){StringBuffer buf = new StringBuffer();buf.append(“Login Successsul - ”);buf.append(“Name:”);buf.append(username);log.debug(bug.toString());}org.apache.commons.logging.LogFactory interface provides two static methods to obtain logger instances:public static Log getLog(String name)throws LogConfigurationException;public static Log getLog(Class class) throws LogConfigurationException;The first getLog() method uses the name parameter as the name of the logger; the second getLog() method uses the name of the class specified by the class parameter as the name of the logger. The following is An implementation of the second getLog() method:public static Log getLog(Class class) throws LogConfigurationException{getLog(class.getName); //call getLog(String name)}Log4J is mainly composed of three major components: Logger, Appender and Layout. Logger controls the output of log information; Appender determines the output destination of log information; Layout determines the output format of log information. Log4J allows users to flexibly configure these components in configuration files. It is very convenient to use Log4J in a program. You only need to obtain the logger first, then read the configuration file and configure the Log4J environment. Then you can call the appropriate method of the Logger class to generate logs wherever you need to output logs in the program.
##log4j.rootLogger =WARN,file,console rootLogger Configure log level , Output purpose;

log4j.appender.file=org.apache.log4jRollingFileAppender

Log4j.appender.file=log.txt

log4j.appender.console=org.apache.log4j.ConsoleAppender

The above is the detailed content of Introduction to the basic usage of Log4j. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!