Java Log Output __java

Source: Internet
Author: User
Tags print format log4j

To add log functionality to the Spring framework:

Pom.xml

1<dependency>
2   <groupId>log4j</groupId>
3   <artifactid>log4j</ Artifactid>
4   <version>1.2.17</version>
5</dependency>

Xml

1   <!--start log-->
 2      <servlet>  
 3         <servlet-name>log4jinitservlet</ Servlet-name>  
 4         <servlet-class>com.rain.log.Log4JInitServlet</servlet-class>  
 5         <init-param>  
 6             <param-name>log4j-properties-location</param-name>  
 7             <param-value>/WEB-INF/log4j.properties</param-value>  
 8         </init-param>  
 9         <load-on-startup>1</load-on-startup>     </servlet>

Log4j.properties

# Root logger option log4j.rootlogger=info, Stdout,errorlog # Direct Log messages to stdout Log4j.appender.stdout=org.apache.log4j.consoleappender log4j.appender.stdout.target=
System.out Log4j.appender.stdout.layout=org.apache.log4j.patternlayout Log4j.appender.stdout.layout.conversionpattern=%d{yyyy-mm-dd HH:mm:ss}%-5p%c{1}:%l-%m%n # Write error logger to error
. log file Log4j.logger.org.springframework = warn  log4j.logger.org.hibernate=warn  Log4j.appender.errorlog = Org.apache.log4j.DailyRollingFileAppender Log4j.appender.errorlog.File =/home/rain/\
U6587\u6863/error.log Log4j.appender.errorlog.Append = True Log4j.appender.errorlog.Threshold = INFO
Log4j.appender.errorlog.layout = Org.apache.log4j.PatternLayout Log4j.appender.errorlog.encoding=utf-8 Log4j.appender.errorlog.layout.ConversionPattern =%d{yyyy-mm-dd HH:mm:ss}%-5p%c{1}:%l-%m%n #%-d{yyyy-mm-dd hh:mm: SS} [%t:%r]-[%p]%m%n 
log4jinitservlet.java 
 1 package com.rain.log;  
 2 3 Import Java.io.File;  
 4 Import java.io.IOException;  
 5 6 Import Javax.servlet.ServletConfig;  
 7 Import Javax.servlet.ServletContext;  
 8 Import javax.servlet.ServletException;  
9 Import Javax.servlet.http.HttpServlet;  
Import Javax.servlet.http.HttpServletRequest;  
Import Javax.servlet.http.HttpServletResponse;  
Import Org.apache.log4j.BasicConfigurator;  
Import Org.apache.log4j.PropertyConfigurator; /** * Servlet Implementation Class Log4jinitservlet the public class Log4jinitservlet extends Htt  
Pservlet {private static final long serialversionuid = 1L; /** * @see httpservlet#httpservlet () * * * Public log4jinitservlet () {SUP  
ER ();  
Constructor/** @see Servlet#init (servletconfig) * */TODO auto-generated Throws public void init (servletconfig config) servletexceptiOn {System.out.println ("Log4jinitservlet Initializing log4j Log settings information");  
Panax Notoginseng String log4jlocation = Config.getinitparameter ("log4j-properties-location");  
ServletContext sc = Config.getservletcontext (); if (log4jlocation = null) {SYSTEM.ERR.PRINTLN ("* * * * No log4j-properties-location initialization files,  
So use basicconfigurator initialization ");  
Basicconfigurator.configure ();  
{} else {a String Webapppath = Sc.getrealpath ("/");  
A String Log4jprop = Webapppath + log4jlocation;  
The file Yomamayesthissaysyomama = new file (Log4jprop); (Yomamayesthissaysyomama.exists ()) {System.out.println ("use: + log4jprop+" Initialization log settings  
Information ");  
Propertyconfigurator.configure (Log4jprop); I else {System.err.println ("* * *" + log4jprop + "File not found, so use basicconfigurator initialization")  
; BasicconfiguraTor.configure ();  
Super.init (config);      /** @see Httpservlet#doget (httpservletrequest request, httpservletresponse response) 61 * protected void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, I oexception {//TODO auto-generated Method Stub/** * @see Httpservlet#dopos T (httpservletrequest request, httpservletresponse response)/protected void DoPost (HttpServletRequest Request, HttpServletResponse response) throws Servletexception, IOException {//TODO auto-generated method s Tub 71} 72 73}

In Java files:

1     Logger Logger=logger.getlogger (GetClass ());
2     logger.info ("info");
3     logger.error ("error");
log4j Basic Use Method

Log4j is composed of three important components: priority of log information, output destination of log information, and output format of log information. Log information priority from high to low have error, WARN, INFO, DEBUG, respectively, to specify the importance of this log information; the output destination of the log information specifies whether the log will be printed to the console or file, and the output format controls the display of the log information.

2.1. Define configuration file

You can actually configure the LOG4J environment in your code without using a configuration file at all. However, using a configuration file will make your application more flexible. LOG4J supports two configuration file formats, one in XML format and one for Java attribute files (key = value). Here's how to use the Java attribute file as a configuration file:
1. Configure the root logger, whose syntax is:

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

Where level is the priority of logging, divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or levels you define. 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 refers to where B log information is exported. You can specify multiple output destinations at the same time.

2. Configuration log information output destination Appender, its syntax is:

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

Among them, LOG4J provides the following appender:

Org.apache.log4j.ConsoleAppender (console),  
org.apache.log4j.FileAppender (file),  
Org.apache.log4j.DailyRollingFileAppender (a log file is generated every day),  
Org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches the specified size),  
Org.apache.log4j.WriterAppender (send log information to any specified place in streaming format)

3. Configure the format (layout) of the log information, and its syntax is:

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

Of these, the log4j provides layout with several e:

Org.apache.log4j.HTMLLayout (layout in HTML table),  
org.apache.log4j.PatternLayout (you can specify layout patterns flexibly),  
Org.apache.log4j.SimpleLayout (The level and information string that contains the log information),  
org.apache.log4j.TTCCLayout (contains information about the time, thread, category, and so on that the log was generated)

LOG4J uses a print format similar to the printf function in c to format the log information, printing parameters as follows:%m the message specified in the output code

%p output priority, that is, the debug,info,warn,error,fatal  
%r output from the application boot to the output of the log information the number of milliseconds the output  
belongs to the class, usually the full name of the class  
%t output the thread name that generated the log event  
%n output A carriage return line break, Windows platform is "RN", UNIX platform is "n"  
%d output log point-in-time date or time, the default format is ISO8601, you can also specify the format after, such as:%d{yyy MMM DD HH:mm:ss, SSS}, output similar to: October 18, 2002 22:10:28,921  
%l output Log event location, including the class name, the thread that occurred, and the number of lines in the code. Example: Testlog4.main (testlog4.java:10)

2.2, the use of log4j in the code

1. Get the Recorder

Using log4j, the first step is to get the logger, which will be responsible for controlling log information. Its syntax is:

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

2. Read the configuration file

When the logger is obtained, the second step configures the LOG4J environment with the following syntax:

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.

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);  
Logger.info (Object message);  
Logger.warn (Object message);  
Logger.error (Object message);

2.3, log level

Each logger is logged at a log level to control the output of the log information. Log levels are divided from high to Low:

A:off the highest level, to turn off all log records.
b:fatal that each serious error event will cause the application to exit.
C:error that although an error event occurs, it still does not affect the continued operation of the system.
D:warm indicates a potential error condition.
E:info generally and at a coarse-grained level, emphasize the full application operation.
F:debug is typically used at fine-grained levels and is very helpful for debugging applications.
G:all lowest level to open all log records.

The above levels are defined in the Org.apache.log4j.Level class. Log4j only recommends 4 levels, from high to low, respectively, Error,warn,info and Debug. By using the logging level, you can control the output of the corresponding level of log information in your application. For example, if you use the info level of B, all log information below the info level in your application, such as debug, will not be printed.

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.