Basic usage Tutorials for Java log software log4j _java

Source: Internet
Author: User
Tags html form rollback socket log4j

1. Overview
1.1 Background
in our daily development, logging is very important. Adding logging in an application in general, it is based on three purposes: monitoring the change of variables in the code, periodically recording to the file for other applications for statistical analysis work, tracking code run-time trajectory as the basis for future audits, as the role of the debugger in the integrated development environment, Debug information that prints code to a file or console.

1.2 Introduction
log4j (log for Java) is an open source project for Apache that provides a fine way to log management. With a configuration file, we can choose to control the output format and destination of each log in more than one way. By defining the level of information, we can also flexibly switch the feedback information in the code. Simply put, log4j is the API class library that helps developers with log output management. Its most important characteristic can configure the file to set the priority of the log information flexibly, the output destination of the log information and the output format of the log information.

2.LOG4J Configuration
Class diagram of the 2.1log4j

    • Logger-log writer for programmers to output log information
    • Appender-Log destinations, output formatted log information to a specified location
    • Consoleappender-Destination for console Appender
    • Fileappender-Appender of the destination file
    • Rollingfileappender-Appender of a file with a destination size Limited
    • Layout-Log formatter, which is used to format the programmer's logging request into a string
    • Patternlayout-Format the logging request with the specified pattern layout

2.2 Defining configuration Files
log4j can be set dynamically through Java programs, the obvious disadvantage of this is that if you need to modify the log output level information, you must modify the Java file, and then recompile, it is troublesome.


Using a configuration file will make our application more flexible in configuring log, which includes output priority, output destination, and output format. LOG4J supports two configuration file formats, one in XML format and one for Java attribute file Log4j.properties (key = value).

    • n XML file
    • n Properties file (recommended)

2.3 Configuration file Log4j.properties
at the first call to Log4j, log4j will be on the classpath (... /web-inf/class/Of course can also be placed in any other directory, as long as the directory is included in the Classpath can be located in this file, and read into the complete configuration of this file. This configuration file tells log4j what format, what kind of information, and where to go. Accordingly, we need to configure 3 aspects of the content:

1, the root directory (level and destination);

2, the destination (console, documents, etc.);

3, output style (how to display the log content)


Examples are as follows:

#设置日志输出级别

Log4j.rootlogger=debug,appender1

#输出到控制台

Log4j.appender.appender1=org.apache.log4j.consoleappender

#样式为TTCCLayout

Log4j.appender.appender1.layout=org.apache.log4j.ttcclayout


2.4.log4j Three components description
Log4j has three main components: loggers (recorder), Appender (output source), and layout (layout). The combination of these three components makes it easy to record the type and level of information and to control the style and location of the log output at run time. The following three components are described separately:

2.4.1 Log Recorder Logger

The Logger object is used to replace the System.out or System.err log writer for the programmer to output log information.


Configure root logger, syntax:

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

Where level is the priority of logging, divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or custom levels. 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. For example, if the info level is defined here, all debug-level log information in the application will not be printed. Appendername is where you specify the output of the log information. Multiple output destinations can be specified at the same time.

2.4.2 Output Destination Appender

The log4j log system allows you to output logs to different places, such as consoles, files, new files based on the number of days or file sizes, streaming to other places, and so on.

Configure Appender, which is represented by the syntax:

Log4j.appender.appenderName = Fully.qualified.name.of.appender.class
Log4j.appender.appenderName.option1 = Value1 ...
Log4j.appender.appenderName.option = Valuen

"Fully.qualified.name.of.appender.class" can specify one of the following five destinations:
1). Org.apache.log4j.ConsoleAppender (console)
2). Org.apache.log4j.FileAppender (file)
3). Org.apache.log4j.DailyRollingFileAppender (Generate a log file every day)
4. Org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches a specified size)
5. Org.apache.log4j.WriterAppender (send log information to any specified place in streaming format)
(1). Consoleappender Options

    • Threshold=warn: Specifies the lowest level of output for log messages.
    • Immediateflush=true: The default value is true, meaning that all messages will be immediately exported.
    • Target=system.err: By default: System.out, specify output console

(2). Fileappender Options

    • Threshold=warn: Specifies the lowest level of output for log messages.
    • Immediateflush=true: The default value is true, meaning that all messages will be immediately exported.
    • File=mylog.log: Specifies the message output to the MyLog.log file.
    • Append=false: The default value is True, the message is incremented to the specified file, and false refers to overwriting the specified file contents with the message.

(3). Dailyrollingfileappender Options

    • Threshold=warn: Specifies the lowest level of output for log messages.
    • Immediateflush=true: The default value is true, which means that all messages will be exported immediately.
    • File=mylog.log: Specifies the message output to the MyLog.log file.
    • Append=false: The default value is True, the message is incremented to the specified file, and false refers to overwriting the specified file contents with the message.
    • Datepattern= '. ' YYYY-WW: Scrolls the file once a week, that is, a new file is generated each week. Of course, you can specify the month, week, day, time, and minutes.

The corresponding format is as follows:
1) '. ' YYYY-MM: Monthly
2) '. ' YYYY-WW: Weekly
3) '. ' YYYY-MM-DD: Every day
4) '. ' Yyyy-mm-dd-a: two times a day
5) '. ' YYYY-MM-DD-HH: Per hour
6) '. ' YYYY-MM-DD-HH-MM: Per minute
4.RollingFileAppender Options

    • Threshold=warn: Specifies the lowest level of output for log messages.
    • Immediateflush=true: The default value is true, which means that all messages will be exported immediately.
    • File=mylog.log: Specifies the message output to the MyLog.log file.
    • Append=false: The default value is True, the message is incremented to the specified file, and false refers to overwriting the specified file contents with the message.
    • MAXFILESIZE=100KB: The suffix can be kb, MB, or GB. When the log file reaches that size, it scrolls automatically, moving the original content to the Mylog.log.1 file.
    • maxbackupindex=2: Specifies the maximum number of scrolling files that can be produced.

2.4.3 Format (layout) Layout

Sometimes you want to format your own log output according to your preferences. Log4j can perform this function by attaching layout to the Appender.

Configure layout, which is represented by the syntax:

Log4j.appender.appenderName.layout =fully.qualified.name.of.layout.class
Log4j.appender.appenderName.layout.option1 = value1
...
Log4j.appender.appenderName.layout.option = Valuen


Layout provides four log output styles, as follows:

(1). org.apache.log4j.HTMLLayout (layout in HTML form),
(2). Org.apache.log4j.PatternLayout (You can specify the layout mode flexibly),
(3). Org.apache.log4j.SimpleLayout (The level and information string that contains the log information),
(4). Org.apache.log4j.TTCCLayout (Contains information about the time, thread, category, etc.) of the log generation

Htmllayout Options
Locationinfo=true: Default value is false, output Java file name and line number
Title=my app File: The default value is log4j Log Messages.
2.PatternLayout Options
conversionpattern=%m%n: Specifies how to format the specified message.

What needs to be explained here is the meaning of several symbols represented in the log Information format:

    • -X: Left-aligned when x information is output
    • %p: Output log information priority, i.e. 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 thereafter, for example:%d{yyy MMM dd hh:mm:ss,sss}, Output is similar: October 18, 2002 22:10:28,921
    • %r: The number of milliseconds to output from the application boot to the output of this log information
    • %c: The class that the output log information belongs to, usually the full name of the class in which it is located
    • %t: Output The name of the thread 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, 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 feed

You can control the minimum width, the maximum width, and the alignment of text by adding modifiers 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 extra characters off.

2.5.LOG4J Configuration Sample
Log4j's simple configuration makes it all over the more and more applications: log4j configuration file to achieve the output to the console, file, rollback files, send log mail, output to the database log table, custom tags and so on a full set of functions.

Log4j.rootlogger=debug,console,a1,im 
Log4j.addivity.org.apache=true

n applies to the console

Log4j.appender.console=org.apache.log4j.consoleappender
Log4j.appender.threshold=debug 
Log4j.appender.console.target=system.out
log4j.appender.console.layout=org.apache.log4j.patternlayout 
log4j.appender.console.layout.conversionpattern=%d-%c-%-4r[%t]%-5p%c%x-%m%n

n Applies to File

Log4j.appender.file=org.apache.log4j.fileappender
Log4j.appender.file.file=file.log
Log4j.appender.file.append=false
log4j.appender.file.layout=org.apache.log4j.patternlayout
log4j.appender.file.layout.conversionpattern=%d-%c-%-4r [%t]%-5p%c%x-%m%n

n Applies to file rollback

Log4j.appender.rolling_file=org.apache.log4j.rollingfileappender
Log4j.appender.ROLLING_FILE. Threshold=error
Log4j.appender.ROLLING_FILE. File=rolling.log
Log4j.appender.ROLLING_FILE. Append=true
Log4j.appender.ROLLING_FILE. MAXFILESIZE=10KB
Log4j.appender.ROLLING_FILE. Maxbackupindex=1
log4j.appender.rolling_file.layout=org.apache.log4j.patternlayout
log4j.appender.rolling_file.layout.conversionpattern=%d-%c-%-4r [%t]%-5p%c%x-%m%n

n applies to the socket

Log4j.appender.socket=org.apache.log4j.rollingfileappender
log4j.appender.socket.remotehost=localhost 
log4j.appender.socket.port=5001
log4j.appender.socket.locationinfo=true 
log4j.appender.socket.layout= Org.apache.log4j.PatternLayout
log4j.appender.socet.layout.conversionpattern=[start]%d{date}[date]%n%p[ priority]%n%x[ndc]%n%t[thread]%n%c[category]%n%m[message]%n%n
# Log Factor 5 appender 
log4j.appender.LF5_ Appender=org.apache.log4j.lf5.lf5appender 
Log4j.appender.LF5_APPENDER. maxnumberofrecords=2000

n Send log to mail

Log4j.appender.mail=org.apache.log4j.net.smtpappender
log4j.appender.mail.threshold=fatal
log4j.appender.mail.buffersize=10
log4j.appender.mail.from=web@www.wuset.com
log4j.appender.mail.smtphost=www.wusetu.com
log4j.appender.mail.subject=log4j 
Message log4j.appender.mail.to=web@www.wusetu.com
log4j.appender.mail.layout=org.apache.log4j.patternlayout 
log4j.appender.mail.layout.conversionpattern=%d-%c-%-4r[%t]%-5p%c%x-%m%n

N for database

Log4j.appender.database=org.apache.log4j.jdbc.jdbcappender
log4j.appender.database.url=jdbc:mysql:// Localhost:3306/test
log4j.appender.database.driver=com.mysql.jdbc.driver 
log4j.appender.database.user= Root
log4j.appender.database.password=
log4j.appender.database.sql=insert into log4j (message) VALUES ('%d- %c-%-4r [%t]%-5p%c%x-%m%n ')
log4j.appender.database.layout=org.apache.log4j.patternlayout 
log4j.appender.database.layout.conversionpattern=%d-%c-%-4r[%t]%-5p%c%x-%m%n
log4j.appender.A1= Org.apache.log4j.DailyRollingFileAppender 
log4j.appender.a1.file=samplemessages.log4j 
Log4j.appender.a1.datepattern=yyyymmdd-hh '. log4j '
log4j.appender.a1.layout=org.apache.log4j.xml.xmllayout

N Custom Appender

log4j.appender.im = Net.cybercorlin.util.logger.appender.IMAppender

log4j.appender.im.host = Mail.cybercorlin.net 
log4j.appender.im.username = username 
log4j.appender.im.password = password 
Log4j.appender.im.recipient = corlin@cybercorlin.net

log4j.appender.im.layout=org.apache.log4j.patternlayout
Log4j.appender.im.layout.ConversionPattern =[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n


3. Configure log4j for spring in a Web application
you first need to include the following configuration statement in the Web.xml file:

 <!--to avoid conflicts between projects, define a unique webapprootkey--> <context-param> <param-name>we bapprootkey</param-name> <param-value>myProject.root</param-value> </context-param> <! --Load log4j configuration file log4j.properties--> <context-param> <param-name>log4jconfiglocation</param-name > <param-value>/WEB-INF/classes/config/log4j/log4j.properties</param-value> </context-param > <!--Set the time interval for refreshing the log configuration file, set to 60s--> <context-param> <param-name>log4jrefreshinterval</param -name> <param-value>60000</param-value> </context-param> <!--load log4j listeners in the Spring framework Log4jcon Figlistener--> <listener> <listener-class>org.springframework.web.util.log4jconfiglistener</ listener-class> </listener> 

The value of the property log4jconfiglocation is recommended or set to:/web-inf/classes/log4j.properties so that we can do some testing to properly log information without starting a WEB application. Log4jconfiglistener is a tool class provided by spring that opens a log4j monitoring thread and detects log configuration changes per Log4jrefreshinterval (definition) second. You do not need to restart the Web service each time to apply the new configuration. The system properties are not separated from Tomcat according to the Web application. So you have to define a unique "Webapprootkey" for each Web application, which we name as Webapp.root. After the environment is started, Log4jconfiglistener injects the value into the Webapp.root variable.

4. Using log4j in your code
4.1. Get the Recorder
using log4j, the first step is to get the logger, which is responsible for controlling log information.

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 ())

4.2. Read the configuration file
when the logger is obtained, the second step configures the LOG4J environment with the following syntax:

If you put the log4j.properties in the engineering root directory or do not write this sentence, the program will automatically find the configuration file.
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.

LOG4J uses the above 3 configurator to initialize, uses Propertyconfigurator to be suitable for all systems. such as the following statement.

Propertyconfigurator.configure ("Log4j.properties");

For General Java project to initialize log4j,log4j without using the above statement, the configuration file is automatically found and initialized under Classpath. If the log4j cannot initialize the configuration file automatically, it needs to be initialized with the above method.

Note: Initializing the configuration file is best done only once when the system is started, if executed multiple times, one is a waste of resources, the other is for the old version of the log4j, the use of dailyrollingfileappender, there may be problems.


4.3. Insert record information (format log information)
when the two necessary steps are completed, you can easily insert any of the different priority logging statements into the places you want to log, with the following syntax:

Logger.debug (Object message);

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.