log4j log output in Java console, simple and practical

Source: Internet
Author: User
Tags log4j

log4j Log output in Java console, simple and practical

1, log4j output has 2 in the way: the first is to save the log information in a text, the second is output to the console. The second way is described below.

2, in the console output log4j log information, is commonly used in development projects is also a must be a technical point.

3, 2 kinds of log4j file loading mode, the following code can be directly used in the project. The theory of things is not more said directly to see the code. Several steps are completed.

Java QQ Group: 180258862

4, prepare log4j-contrl.propertes file, its catalogue is src/log4j-contrl.propertes:

log4j.appender.encoding = UTF-8
Log4j.rootlogger=info,console,applog,error,errorlog
#log4j. Rootlogger=error,errorlog
Log4j.appender.console=org.apache.log4j.consoleappender
Log4j.appender.console.target=system.out
Log4j.appender.console.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.CONSOLE.LAYOUT.CONVERSIONPATTERN=%D{YYYY-MM-DD HH:mm:ss}%-5p [%t]%c%x-%m%n

Log4j.appender.applog=org.apache.log4j.dailyrollingfileappender
Log4j.appender.applog.append=true
Log4j.appender.applog.datepattern= ' _ ' yyyyMMdd '. Log '
Log4j.appender.applog.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.APPLOG.LAYOUT.CONVERSIONPATTERN=%D{YYYY-MM-DD HH:mm:ss}%-5p [%t]%c%x-%m%n
Log4j.appender.applog.file=/data1/logs/tomcat/sync/appaccesslog

Log4j.appender.adminlog=org.apache.log4j.dailyrollingfileappender
Log4j.appender.adminlog.append=true
Log4j.appender.adminlog.datepattern= ' _ ' yyyyMMdd '. Log '
Log4j.appender.adminlog.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.ADMINLOG.LAYOUT.CONVERSIONPATTERN=%D{YYYY-MM-DD HH:mm:ss}%-5p [%t]%c%x-%m%n
Log4j.appender.adminlog.file=/data1/logs/tomcat/sync/adminaccesslog

Log4j.appender.errorlog=org.apache.log4j.dailyrollingfileappender
Log4j.appender.errorlog.threshold=error
Log4j.appender.errorlog.append=true
Log4j.appender.errorlog.datepattern= ' _ ' yyyyMMdd '. Log '
Log4j.appender.errorlog.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.ERRORLOG.LAYOUT.CONVERSIONPATTERN=%D{YYYY-MM-DD HH:mm:ss}%-5p [%t]%c%x-%m%n
Log4j.appender.errorlog.file=/data1/logs/tomcat/sync/apperrorlog

Log4j.logger.com.ibatis = DEBUG
Log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = DEBUG
Log4j.logger.com.ibatis.common.jdbc.ScriptRunner = DEBUG
Log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = DEBUG
Log4j.logger.java.sql.Connection = DEBUG
Log4j.logger.java.sql.Statement = DEBUG
Log4j.logger.java.sql.PreparedStatement = DEBUG
Log4j.logger.java.sql.ResultSet = DEBUG


5. Create a servlet to start the log file and load and initialize the log file when the server is started :

Import java.io.IOException;
Import Java.io.PrintWriter;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.log4j.Logger;
Import Org.apache.log4j.PropertyConfigurator;
/**
* log4j console file output, initializing configuration file
* @author Administrator
*
*/
public class Log4jinit extends HttpServlet {

public void Destroy () {
Super.destroy ();
}
public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {}


public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {}

public void Init () throws Servletexception {
String prefix = Getservletcontext (). Getrealpath ("/");
String file = Getservletconfig (). Getinitparameter ("log4j"); is the parameter in the Web.xml
if (file!= null) {
Propertyconfigurator.configure (prefix + file);
}
Logger log = Logger.getlogger (Log4jinit.class);
Log.info ("logg4j log has been initialized.) ");
}
}

6. Configure the servlet in Web.xml and initialize the Servelt file:

<servlet>
<servlet-name>Log4jInit</servlet-name>
<servlet-class>com.java.log.Log4jInit</servlet-class>
<init-param>
<param-name>log4j</param-name>
<param-value>WEB-INF/classes/log4j-contrl.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>Log4jInit</servlet-name>
<url-pattern>/log/logfj</url-pattern>
</servlet-mapping>

7, Test log4j log (here test can only be accessed through the web in the ability to output log, in the main method does not seem to be the case but can be described in the following method (sequence 9) can):

Import java.io.IOException;
Import Java.io.PrintWriter;
Import java.io.UnsupportedEncodingException;
Import java.security.InvalidKeyException;
Import java.security.NoSuchAlgorithmException;
Import javax.crypto.BadPaddingException;
Import javax.crypto.IllegalBlockSizeException;
Import javax.crypto.NoSuchPaddingException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.log4j.Logger;
Import Org.apache.log4j.PropertyConfigurator;

public class Log4j extends HttpServlet {
private static final transient Logger log = Logger.getlogger (log4j. Class);

public void Destroy () {
Super.destroy ();
}


public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
DoPost (request, response);
}


public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {

Response.setcontenttype ("Text/html;charset=utf-8");
PrintWriter out = Response.getwriter ();
Log.info ("Log information, will be output in the console");
Log.error ("Can record error message, output font for control");
Out.flush ();
Out.close ();
}
public void Init () throws Servletexception {

}
}

8. Output Result:

2013-05-01 14:08:55 info [http-9090-1] Com.java.md.KeyMDF-log information, will be output in the console
2013-05-01 14:08:55 error [http-9090-1] Com.java.md.KeyMDF-can log error messages, output fonts for control


9, the second way to load the Log4j-contrl.propertes file:

Import Org.apache.log4j.Logger;

Import Org.apache.log4j.PropertyConfigurator;

public class Testlog4j {

private static final transient Logger log = Logger.getlogger (testlog4j. Class);

public static void Main (string[] args) throws InvalidKeyException, Illegalblocksizeexception, nosuchalgorithmexception , Unsupportedencodingexception, Badpaddingexception, nosuchpaddingexception {

Propertyconfigurator.configure ("Src/log4j.properties");
Log.info ("Log information, will be output in the console");
Log.error ("Can record error message, output font for control");
}

}






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.