使用apache commons-email將錯誤日誌發送到指定郵箱

原文地址:http://ketayao.com/view/33html

  web開發,有個場景,但願將錯誤日誌發送到指定郵箱,這樣能夠作到遠程監控,實時處理。下面寫一個利用apache commons email的例子,發送錯誤日誌的例子。java

001 /**
002  
003  * @author  <a href="mailto:ketayao@gmail.com">ketayao</a>
004  * @since   2013年9月7日 下午6:27:05
005  */
006  
007 public class EmailExceptionHandler extends ExceptionHandler {
008      
009     private static final Logger log = LoggerFactory.getLogger(EmailExceptionHandler.class);
010      
011     /**
012      * 報告錯誤信息
013      * @param req
014      * @param excp
015      */
016     public static void reportError(HttpServletRequest req, Throwable excp){
017         boolean is_localhost = (req!=null)?"127.0.0.1".equals(RequestUtils.getRemoteAddr(req)):false;
018         Throwable t = excp;
019         if(t == null) t = _getException(req);
020         if(t == nullreturn ;
021      
022         log.error("System Exception", t);
023         if(!is_localhost)
024         //發送電子郵件通知
025         try {
026             String email = SystemConfig.getConfig().get("blog.exception.email.to");
027             String title = "錯誤" + t.getClass().getSimpleName();
028             String content = getErrorHtml(req, t);
029             //發送郵件到指定郵箱
030             _sendHtmlMail(Arrays.asList(StringUtils.split(email,",")), title, content);
031         catch (Exception e) {
032             log.error("Failed to send error report.", e);
033         }
034     }
035      
036     /** 
037      * 描述
038      * @param asList
039      * @param title
040      * @param content 
041      * @throws Exception
042      */
043     private static void _sendHtmlMail(List<String> emailAddress, String title,
044             String content) throws Exception {
045         for (String address : emailAddress) {
046             HtmlEmail email = new HtmlEmail();
047             email.setStartTLSEnabled(true);
048             email.setHostName(SystemConfig.getConfig().get("blog.exception.email.hotname"));
049             email.setAuthentication(SystemConfig.getConfig().get("blog.exception.email.name"),
050                     SystemConfig.getConfig().get("blog.exception.email.password"));
051             email.setFrom(SystemConfig.getConfig().get("blog.exception.email.name"));
052  
053             email.addTo(address);
054              
055             email.setSubject(title);
056             // set the html message
057             email.setHtmlMsg(content);
058             // set the alternative message
059             email.setTextMsg("Your email client does not support HTML messages");
060              
061             email.send();
062         }
063     }
064  
065     /**
066      * 格式化錯誤信息
067      * @param req
068      * @param t 錯誤信息
069      * @param site 出錯的我的空間
070      * @return
071      * <h2>Request Headers</h2>
072      */
073     @SuppressWarnings("rawtypes")
074     public static String getErrorHtml(HttpServletRequest req, Throwable t) {
075         StringBuilder html = new StringBuilder();
076         if(req != null){
077             html.append("<h2>Request Headers</h2><table>");  
078             html.append("<tr><th>Request URL</th><td>");
079             html.append(req.getRequestURL().toString());
080             if(req.getQueryString()!=null){
081                 html.append('?');
082                 html.append(req.getQueryString());                     
083             }
084             html.append("</td></tr>");
085             html.append("<tr><th>Remote Addr</th><td>");
086             html.append(RequestUtils.getRemoteAddr(req));
087             html.append("</td></tr>");
088             html.append("<tr><th>Request Method</th><td>");
089             html.append(req.getMethod());
090             html.append("</td></tr>");
091             html.append("<tr><th>CharacterEncoding</th><td>");
092             html.append(req.getCharacterEncoding());
093             html.append("</td></tr>");
094             html.append("<tr><th>Request Locale</th><td>");
095             html.append(req.getLocale());
096             html.append("</td></tr>");
097             html.append("<tr><th>Content Type</th><td>");
098             html.append(req.getContentType());
099             html.append("</td></tr>");
100             Enumeration headers = req.getHeaderNames();
101             while(headers.hasMoreElements()){
102                 String key = (String)headers.nextElement();
103                 html.append("<tr><th>");
104                 html.append(key);
105                 html.append("</th><td>");
106                 html.append(req.getHeader(key));
107                 html.append("</td></tr>");
108             }      
109             html.append("</table><h2>Request Parameters</h2><table>");     
110             Enumeration params = req.getParameterNames();
111             while(params.hasMoreElements()){
112                 String key = (String)params.nextElement();
113                 html.append("<tr><th>");
114                 html.append(key);
115                 html.append("</th><td>");
116                 html.append(req.getParameter(key));
117                 html.append("</td></tr>");
118             }
119             html.append("</table>");
120         }
121         html.append("<h2>");
122         html.append(t.getClass().getName());
123         html.append('(');
124         html.append(DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
125         html.append(")</h2><pre>");
126         try {
127             html.append(_exception(t));
128         catch (IOException ex) {}
129         html.append("</pre>");
130      
131         html.append("<h2>System Properties</h2><table>");    
132         Set props = System.getProperties().keySet();
133         for(Object prop : props){
134             html.append("<tr><th>");
135             html.append(prop);
136             html.append("</th><td>");
137             html.append(System.getProperty((String)prop));
138             html.append("</td></tr>");
139         }
140         html.append("</table>");
141         return html.toString();
142     }
143      
144     /**
145      * 將當前上下文發生的異常轉爲字符串
146      * @return
147      * @throws IOException
148      */
149     private static Throwable _getException(HttpServletRequest req) {
150         if(req == nullreturn null;
151         Throwable t = (Throwable)req.getAttribute("javax.servlet.jsp.jspException");
152         if(t==null){
153             //Tomcat的錯誤處理方式
154             t = (Throwable)req.getAttribute("javax.servlet.error.exception");
155         }
156         return t;
157     }
158      
159     /**
160      * 將異常信息轉化成字符串
161      * @param t
162      * @return
163      * @throws IOException
164      */
165     private static String _exception(Throwable t) throws IOException{
166         if(t == null)
167             return null;
168         ByteArrayOutputStream baos = new ByteArrayOutputStream();
169         try{
170             t.printStackTrace(new PrintStream(baos));
171         }finally{
172             baos.close();
173         }
174         return baos.toString();
175     }
176  
177     /**  
178      * @param rc
179      * @param exception
180      * @return 
181      * @see com.ketayao.fensy.handler.Handler#handle(com.ketayao.fensy.mvc.RequestContext, java.lang.Exception) 
182      */
183     @Override
184     public String handle(final RequestContext rc, final Exception exception) {
185         String view = super.handle(rc, exception);
186          
187         Thread thread = new Thread(new Runnable() {
188              
189             @Override
相關文章
相關標籤/搜索