項目經常使用工具類整理(四)--日誌管理

還得按套路來,繼續寫個人白開水博客java

第一步:引入jar包web

<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.2</version>
		</dependency> 
  		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>1.1.2</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>1.7.5</version>
		</dependency>

若是我告訴你:我在個人controller或是Service裏面直接sql

private static Logger logger = Logger.getLogger(Test.class);

你是否是就不往下看了?然而並非,仍是要有點兒乾貨的。apache

第二步:在web.xml中配置一個Servlettomcat

<servlet>
	    <servlet-name>log4j-init</servlet-name>  
	    <servlet-class>com.common.util.Log4jInit</servlet-class>  
	    <init-param>  
	        <param-name>log4j-init-file</param-name>  
	        <param-value>/WEB-INF/classes/log4j.properties</param-value>  
	    </init-param>  
	    <load-on-startup>3</load-on-startup>  
    </servlet>

下面詳細講一下這個配置中的內容mybatis

一、貼出Log4jInit的源碼app

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.PropertyConfigurator;

/**
 * Servlet implementation class Log4jInit
 */
public class Log4jInit extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doPost(req, resp);
	}

	@Override
	public void init() throws ServletException {
		super.init();
		String prefix = getServletContext().getRealPath("/");
		String file = getInitParameter("log4j-init-file");
		if (file != null) {
			System.out.println("read log4j.properties:"+prefix + file);
			PropertyConfigurator.configure(prefix + file);
		}
	}

}

二、關於log4j.properties的位置,這個可能要根據你本身項目的位置來微調,同時你採用的服務有關,tomcat和jboss是不同的,其餘的沒試過ide

<param-value>/WEB-INF/classes/log4j.properties</param-value>

三、如今應該貼一下log4j.properties中的內容了函數

################ OFF ,FATAL ,ERROR ,WARN ,INFO ,DEBUG ,ALL
log4j.rootLogger=ERROR, stdout, D
### \u628A\u65E5\u5FD7\u4FE1\u606F\u8F93\u51FA\u5230\u63A7\u5236\u53F0 ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss} method:%l%n%m%n

### \u628A\u65E5\u5FD7\u4FE1\u606F\u8F93\u51FA\u5230\u6587\u4EF6\uFF1Alog.log ###
#log4j.appender.C.Threshold=WARN
#RollingFileAppender\u4E3A\u5FAA\u73AF\u8986\u76D6\u6A21\u5F0F\uFF0C\u5907\u4EFD\u6587\u4EF6\u4E2A\u6570\u4E3AMaxBackupIndex\u6307\u5B9A\u7684\u503C
log4j.appender.D=org.apache.log4j.RollingFileAppender
#log4j.appender.D=org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File=${catalina.home}/logs/log.log
log4j.appender.D.MaxFileSize=1MB
# Keep one backup file
log4j.appender.D.MaxBackupIndex=100
log4j.appender.D.layout=org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH\:mm\:ss} method\:%l%n%m%n 

###\u663E\u793Amybatis SQL\u8BED\u53E5\u90E8\u5206,\u8FD8\u9700\u5C06log4j.rootLogger\u8BBE\u4E3ADEBUG
log4j.logger.com.ibatis=ERROR
log4j.logger.org.apache.ibatis.jdbc.ScriptRunner=ERROR
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

其中log4j.rootLogger對應的日誌級別debug/info/error的級別我就不叨叨了。叨叨一下這個this

private static Logger logger = Logger.getLogger(Test.class);
logger.error(">>----"+entry.getKey().substring(1)+"********失敗!!!");

記錄日誌儘可能寫logger.error,若是你寫了logger.info在debug的模式下,日誌多是打不出來了,若是你非要較真,確定是要重寫log4j.properties的。

四、普及一下web.xml配置中的這句話

<load-on-startup>3</load-on-startup>

我特地查了一下,官方的解釋應該以下:

Servlet specification:
The load-on-startup element indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the web application. The optional contents of these element must be an integer indicating the order in which the servlet should be loaded. If the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses.   If the value is a positive integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-start-up value.

  • load-on-startup標記容器是否在啓動的時候實例化並調用其init()方法的優先級。

  • 它的值表示servlet應該被載入的順序

  • 當值爲0或者大於0時,表示容器在應用啓動時就加載並初始化這個servlet;

  • 若是值小於0或未指定時,則表示只有在第一次請求的容器纔在該servlet調用初始化函數

  • 正值越小,servlet的優先級越高,應用啓動時就越先加載。

  • 值相同時,容器就會本身選擇順序來加載。

因此,<load-on-startup>x</load-on-startup>,中x的取值1,2,3,4,5表明的是優先級,而非啓動延遲時間。

五、下班啦。。。

相關文章
相關標籤/搜索