1. 程式人生 > >強大的log4j,錯誤資訊自動傳送至郵箱

強大的log4j,錯誤資訊自動傳送至郵箱

      前幾天看師兄都不用看伺服器,天天盯著郵箱看就能知道程式碼哪裡出問題了。手癢,我就試試,寫了一個小的程式Java的

匯入jar檔案

                                                 log4j-1.2.1.jar

                                                 activation.jar

                                                 mail.jar

專案結構:

                                                                                          


log4j.properties

log4j.appender.infoR.Append = true
log4j.appender.infoR.Threshold = INFO
#log4j.appender.infoR.DatePattern='_'yyyy-MM-dd-HH'.log'
log4j.appender.infoR.layout = org.apache.log4j.PatternLayout  
log4j.appender.infoR.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [ %l ] %m%n  
  
#errorR  
log4j.appender.errorR = org.apache.log4j.DailyRollingFileAppender  
log4j.appender.errorR.File =f:/errorLog.txt  
log4j.appender.errorR.Append = true  
log4j.appender.errorR.Threshold = ERROR
#log4j.appender.errorR.DatePattern='_'yyyy-MM-dd-HH'.log'
log4j.appender.errorR.layout = org.apache.log4j.PatternLayout  
log4j.appender.errorR.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [ %l ] %m%n  
## MAIL
log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender
log4j.appender.MAIL.Threshold=ERROR
log4j.appender.MAIL.BufferSize=512
log4j.appender.MAIL.SMTPHost=smtp.sina.cn
log4j.appender.MAIL.Subject=\u522B\u6CE1\u59B9\u5B50\u4E86\uFF0C\u8D76\u7D27\u4FEE\u7406\u670D\u52A1\u5668
[email protected]
log4j.appender.MAIL.SMTPPassword=aasd6778246995 [email protected] [email protected] log4j.appender.MAIL.layout=test.Logger4jHTMLLayout log4j.appender.MAIL.layout.ConversionPattern=[ErrorMessage] %d - %c -%-4r [%t] %-5p %c %x - %m%n

Logger4jHTMLLayout.jave
import org.apache.log4j.HTMLLayout;

/**
 * author:zhanglu
 * 2015年9月14日
 * 下午5:19:58
 */
public class Logger4jHTMLLayout extends HTMLLayout {

	@Override
    public String getContentType() {
        return "text/html;charset=utf-8"; 
    }
}

checkLog4j1.java   測試類
import org.apache.log4j.Logger;

/**
 * author:zhanglu
 * 2015年9月14日
 * 下午4:50:15
 */
public class checkLog4j1 {
	private static Logger info = Logger.getLogger("InfoLogger");  
    private static Logger error = Logger.getLogger("ErrorLogger");  
	public static void main(String[] args) {
		
		error.error("sdadfwf");
	}
}

執行,郵箱收到如下郵件

注意,大家一定要重寫getContentType方法,防止亂碼