Advantages and proper configuration of log4j

Source: Internet
Author: User
Tags file size log4j

1 Background information
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.
The most common approach is to embed a number of print statements in your code that can be exported to a console or file, preferably by constructing a log action class to encapsulate such operations, rather than having a series of print statements flooded with the body of the code.
If the program used a lot of system.out, if the day I do not want to print out these debugging information, then I let the whole program in a sentence of the comment out, and a few days I want to print out, that again and again to remove, the workload can be imagined.

2 log4j Profile
In emphasizing reusable component development today, in addition to developing a reusable log operation class from beginning to end, Apache provides us with a powerful log-handling package-log4j.
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, and by defining the level of each log information, we can control the log generation process more carefully. Most interesting of all, these can be configured flexibly with a single configuration file without the need to modify the applied code.
In addition, by log4j other language interfaces, you can use log4j in C, C + +,. Net, and Pl/sql programs, and its syntax and usage, as in Java programs, make a unified and consistent Log component module for a multilingual distributed system. Also, by using a variety of third-party extensions, you can easily integrate log4j into Java EE, Jini, and even SNMP applications.
Therefore, the use of the advantages of log4j: can easily control the log information is displayed, log information output type, output mode, output format, more detailed control of the log generation process, and its configuration file can be flexibly configured without the need for a large number of change code.

3 Use and configuration of log4j
Log4j has three main components, respectively:
*logger (Recorder): Responsible for filtering the log information according to the set priority, then forwarding to the depository
*appender (Depository): Responsible for receiving and processing log information that is forwarded by the logger, usually with output to the screen or to a disk file
*layout (Layout): Responsible for formatting log information
The relationship between the above three:
A logger can hook up multiple appender (log information is forwarded to multiple devices at the same time)
A appender specifies a layout for formatting operations

First, define the configuration file Log4j.properties
1.
log4j. Recorder name =[level], depository name 1, depository Name 2, ...
Level precedence from high to low is: off, FATAL, ERROR, WARN, INFO, DEBUG, all
LOG4J recommends using only four levels, from highest to lowest priority: ERROR, WARN, INFO, DEBUG
Only log information with a priority higher than or equal to the set level is forwarded, for example, if the definition is info, the log information at level debug in the program is not output.
Log4j.rootlogger is the parent object of all loggers (formerly known as Rootcategory), which can be used to set the default priority of all loggers
Loggers can inherit, such as: Log4j.mylogger.childlogger=,file
Logger is obtained by name and automatically created on first access (always exists)
If you contract each class to output logs to only the logger with the same name, you can log configuration for each specific class in the configuration file
2.
Log4j.appender. Depository Name = Repository Class name
Currently, log4j implements the following types of repositories:
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.
Log4j.appender. The name of the depository. Layout= Designer class name
Currently, the log4j implements the following types of layouts:
Org.apache.log4j.PatternLayout (log4j's standard layout allows you to specify layout patterns flexibly)
Org.apache.log4j.HTMLLayout (layout in HTML tabular format)
Org.apache.log4j.SimpleLayout (simple string containing level and log information)
Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, and so on that the log was generated)
4.
Set the layout options (mainly to set the conversion format)
Log4j.appender. Depository name. layout. Option NAME = value

The log4j standard layout is usually used:
Log4j.appender. The name of the depository. Layout=org.apache.log4j.patternlayout
Log4j.appender. The name of the depository. layout.conversionpattern= Formatting parameters

log4j format the log information using a format parameter similar to the printf function in C, with the following parameters:
%m the information specified in the output code
%p output priority, i.e. Debug,info,warn,error,fatal
The number of milliseconds that the%r output has been constructed from the layout to that point in time
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 break, the Windows platform is "/r/n", and the UNIX platform is "/n"
%d output the date or time of the point, the default format is ISO8601, or you can specify a format thereafter. such as:%d{yyy MMM dd hh:mm:ss,sss}, Output class

Like: 82 months 03 12:04:52,531
%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. such as: Testlog4.main (TESTLOG4.JAVA:10)
%F Output File name
%l Output Line number

Second, call log4j in code
1. Import the log4j jar package (Log4j-1.2.15.jar) into the project.
2. Write configuration file log4j.properties, placed in the SRC directory, the system runs automatically copy to the bin directory.

Java code

1.<span style= "Font-family:courier new,courier;" >
2. Import Org.apache.log4j.Logger;
3...
4.private static final Logger log = Logger.getlogger (class name. Class);
5...
6. Log.debug (Object message);
7. Log.info (Object message);
8. Log.warn (Object message);
9. Log.error (Object message);
10.
11.</span>
Import Org.apache.log4j.Logger;
...
Private static final Logger log = Logger.getlogger (class name. classes);
...
Log.debug (Object message);
Log.info (Object message);
Log.warn (Object message);
Log.error (Object message);


Iii. Examples of log4j.properties

XML code

1.< span style = "font-family:courier new,courier;" >
2.# Set Root Logger priority to the INFO and its only appender to CONSOLE.
3.log4j.rootlogger =info, CONSOLE
4.log4j.rootlogger =info, CONSOLE, LOGFILE
5.
6.# Set The Enterprise Logger category to FATAL and it only appender to CONSOLE.
7.log4j.logger.org.apache.axis.enterprise =fatal, CONSOLE
8.
9.# CONSOLE is set to be a consoleappender using a patternlayout.
10.log4j.appender.console =org. Apache.log4j.ConsoleAppender
11.log4j.appender.console.threshold =info
12.log4j.appender.console.layout =org. apache.log4j.PatternLayout
13.
14.# to output the caller ' s file name and line number.
15.log4j.appender.console.layout.conversionpattern =%5p [%t] (%f:%l)-%m%n
16.
17.# LOGFILE is set to be a File appender using a patternlayout.
18.log4j.appender.logfile =org. Apache.log4j.FileAppender
Log4j.appender.LOGFILE.File =axis. Log
20.log4j.appender.logfile.append =true
21.log4j.appender.logfile.threshold =info
22.log4j.appender.logfile.layout =org. apache.log4j.PatternLayout
23.log4j.appender.logfile.layout.conversionpattern =%-4r [%t]%-5p%c%x-%m%n
24.</span >


# Set Root Logger priority to INFO and it only appender to CONSOLE.
Log4j.rootlogger=info, CONSOLE
Log4j.rootlogger=info, CONSOLE, LOGFILE

# Set The Enterprise Logger category to FATAL and it only appender to CONSOLE.
Log4j.logger.org.apache.axis.enterprise=fatal, CONSOLE

# CONSOLE is set to be a consoleappender using a patternlayout.
Log4j.appender.console=org.apache.log4j.consoleappender
Log4j.appender.console.threshold=info
Log4j.appender.console.layout=org.apache.log4j.patternlayout

# to output the caller ' s file name and line number.
log4j.appender.console.layout.conversionpattern=%5p [%t] (%f:%l)-%m%n

# LOGFILE is set to be a File appender using a patternlayout.
Log4j.appender.logfile=org.apache.log4j.fileappender
Log4j.appender.logfile.file=axis.log
Log4j.appender.logfile.append=true
Log4j.appender.logfile.threshold=info
Log4j.appender.logfile.layout=org.apache.log4j.patternlayout
log4j.appender.logfile.layout.conversionpattern=%-4r [%t]%-5p%c%x-%m%n


Iv. Common Failures

Log4j:warn Please initialize the log4j system properly.
Solution:
The Eclipse environment copies the file log4j.properties to the SRC directory, and the runtime is automatically copied to the Bin directory. You may need to refresh before.

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.