使用apache commons-email将错误日志发送到指定邮箱

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

  web开发,有个场景,希望将错误日志发送到指定邮箱,这样可以做到远程监控,实时处理。下面写一个利用apache commons email的例子,发送错误日志的例子。

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
190             public void run() {
191                 reportError(rc.request(), exception);
192             }
193         });
194         thread.start();
195          
196         return view;
197     }
198  
199 }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值