Talking about how to use log4j to log logs

Source: Internet
Author: User

I. What is LOG4J

Log4j is an open source project for Apache. By using log4j, programmers can control the destination of log information delivery, including consoles, files, GUI components, and NT event loggers, and can control the output format of each log, or control the log generation process more carefully by defining the level of each log message.

Two. Logs and classifications

The operation of the software can not be separated from the log, the log is mainly used to record some important operational information during the operation of the system, to facilitate monitoring of the operation of the system, to help users to detect and avoid possible problems in advance, or problems after the log to find the cause of the occurrence.

Depending on the record, the log is divided into three main categories:

1.SQL log: Records the SQL statements executed by the system.

2. Exception log: Records abnormal events that occur during system operation.

3. Business log: Record system running process, such as user's login, operation record.

Three. Configuration file description

1. Define the configuration file
log4j supports two configuration file formats, one in XML format and one Java attribute file Log4j.properties (key = value). The following describes how to use the Log4j.properties file as a configuration file:
① Configuring the root logger
Logger is responsible for most of the operations that log records are processed.
its syntax is:
Log4j.rootlogger = [level], Appendername, Appendername, ...
level is the priority of logging, which is divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or custom levels. LOG4J recommends using only four levels, with the priority from high to low being error, WARN, INFO, DEBUG. By defining the level here, you can control the switch to the appropriate level of log information in your application. For example, if the info level is defined here, only if it is equal to or above that level, the log information for all debug levels in the application will not be printed. All: Print all logs, off: Turns off all log output. Appendername is where you specify where the log information is exported. Multiple output destinations can be specified at the same time.
② Configuration log information output destination Appender
The Appender is responsible for controlling the output of logging operations.
its syntax is:
log4j.appender.appenderName = Fully.qualified.name.of.appender.class
Log4j.appender.appenderName.option1 = value1
Log4j.appender.appenderName.optionN = Valuen
here the appendername is defined in the ①, can be arbitrarily named.
among them, LOG4J provides the following types of Appender:
Org.apache.log4j.ConsoleAppender (console),
org.apache.log4j.FileAppender (file),
org.apache.log4j.DailyRollingFileAppender (generates a log file every day),
Org.apache.log4j.RollingFileAppender (creates a new file when the file size reaches the specified size), the file size can be set by LOG4J.APPENDER.R.MAXFILESIZE=100KB, You can also set to save a backup file via Log4j.appender.r.maxbackupindex=1.
Org.apache.log4j.WriterAppender (send log information in stream format to any specified location)
Example: Log4j.appender.stdout=org.apache.log4j.consoleappender
define an output destination named stdout, Consoleappender as the console.
③ Configuration Log Information Format (layout) layout
layout is responsible for formatting the output of the Appender.
its syntax is:
log4j.appender.appenderName.layout = Fully.qualified.name.of.layout.class
Log4j.appender.appenderName.layout.option1 = value1
... ..
Log4j.appender.appenderName.layout.optionN = Valuen
among them, log4j offers the following types of layout:
org.apache.log4j.HTMLLayout (Layout in HTML table Form),
Org.apache.log4j.PatternLayout (flexibility to specify layout mode),
Org.apache.log4j.SimpleLayout (contains the level of log information and the information string),
Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, etc.) of the log
2. Format log Information
log4j Formats the log information in a print format similar to the printf function in C, with the following printing parameters:
%m The message specified in the output code
%p output priority, i.e. Debug,info,warn,error,fatal
%r Output The number of milliseconds that the log information is consumed from the application boot to output
%c output belongs to the class, which is usually the full name of the class
%t Output The name of the thread that generated the log event
%n output A carriage return newline character, Windows platform is "RN", UNIX platform is "n"
%d the date or time of the output log time, the default format is ISO8601, can also be specified after the format, such as:%d{yyyy MMM dd hh:mm:ss,sss}, output similar: October 18, 2002 22:10:28,921
%l where the output log event occurs, including the class name, the thread that occurred, and the number of rows in the code.

Four. How to log logs using log4j

To use log4j logging, first download the log4j jar file, the official website is http://logging.apache.org/log4j. Current: http://logging.apache.org/log4j/1.2/dowload.html. Download the file and unzip it with a Apache-log4j-1.2.17\log4j-1.2.17.jar file.

First step: Add the jar file used by log4j in the project

First create a Lib folder in the project and copy the file into the file. Then right-click on the jar package that has been copied, select BuildPath--------"Add to Build Path and you'll see one more project in the project: Library

Step two: Create a log4j.properties file

Select the LOG4J project you want to use, click SRC, select New ———— file---------new file--------Enter a file name, click the Finish button to end the creation. ‘

Step three: Write the log4j.properties file and configure the log information.

Log4j.rootlogger=info,file, stdout### Direct log messages to stdout # # #log4j. Appender.stdout=Org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=Org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{absolute}%5p%c{1}:%l-%m%n### Direct messages to File MyLog.log # # #log4j. Appender.file=Org.apache.log4j.FileAppenderlog4j.appender.file.File=D\:mylog.loglog4j.appender.file.layout=Org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern=%d{absolute}%5p%c{1}:%l-%m%n### set Log levels- forMore verbose Logging "info" to ' Debug ' # # #

Five. Logs and Levels

Each logger is logged at a log level to control the output of the log information. The log level is divided from high to Low:
01.off highest level for closing all log records.
02.fatal indicates that each serious error event will cause the application to exit.
03.error indicates that although an error event occurs, it still does not affect the system's continued operation.
04.warm indicates that a potential error condition occurs.
05.info general and at the coarse-grained level, emphasis is placed on the entire application run.
06.debug is generally used for fine-grained levels and is very helpful for debugging applications.
07.all lowest level for opening all log records.

Six. Using lpg4j to log logs in the program

 PackageCn.hyj.one;ImportOrg.apache.log4j.Logger; Public classTest {//get a Loogger instance from logger's GetLogger     Public StaticLogger Lo=logger.getlogger (Test.class);  Public Static voidMain (string[] args) {Try {            intresult=5/0;//An exception occurred}Catch(Exception e) {System.out.println ("The divisor cannot be zero!" "); Lo.info ("Divisor cannot be 0");//Save Log        }      }}

Talking about how to use log4j to log logs

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.