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

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

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

001 /**
002  
003  * @author  ketayao
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 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      *

Request Headers

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("

Request Headers

");  
078             html.append("
Request URL");
079             html.append(req.getRequestURL().toString());
080             if(req.getQueryString()!=null){
081                 html.append('?');
082                 html.append(req.getQueryString());                     
083             }
");
084             html.append("
085             html.append("
Remote Addr");
086             html.append(RequestUtils.getRemoteAddr(req));
");
087             html.append("
088             html.append("
Request Method");
089             html.append(req.getMethod());
");
090             html.append("
091             html.append("
CharacterEncoding");
092             html.append(req.getCharacterEncoding());
");
093             html.append("
094             html.append("
Request Locale");
095             html.append(req.getLocale());
");
096             html.append("
097             html.append("
Content Type");
098             html.append(req.getContentType());
");
099             html.append("
100             Enumeration headers = req.getHeaderNames();
101             while(headers.hasMoreElements()){
102                 String key = (String)headers.nextElement();
103                 html.append("
");
104                 html.append(key);
105                 html.append("");
106                 html.append(req.getHeader(key));
");
107                 html.append("
108             }      
109             html.append("

Request Parameters

");     
110             Enumeration params = req.getParameterNames();
111             while(params.hasMoreElements()){
112                 String key = (String)params.nextElement();
113                 html.append("
");
114                 html.append(key);
115                 html.append("");
116                 html.append(req.getParameter(key));
");
117                 html.append("
118             }
119             html.append("
"
);
120         }
121         html.append("

");

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(")
");
126         try {
127             html.append(_exception(t));
128         catch (IOException ex) {}
129         html.append("");
130      
131         html.append("

System Properties

");    
132         Set props = System.getProperties().keySet();
133         for(Object prop : props){
134             html.append("
");
135             html.append(prop);
136             html.append("");
137             html.append(System.getProperty((String)prop));
");
138             html.append("
139         }
140         html.append("
"
);
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

你可能感兴趣的:(java高级)