jboss7为logging 配置SMTP

1 篇文章 0 订阅
1 篇文章 0 订阅

我用的jboss版本是7.1.1,在这个版本中是没有可配置的日志邮件系统,需要自己去写一个,然后加入到jboss的日志链中。

 如果没有什么特别的要求,可以使用我提供这个。

package com.jll;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
 
import java.util.Date;
import java.util.Hashtable;
import java.util.logging.ErrorManager;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
 
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
 
public class EmailHandler extends Handler {
 
     private Session mailSession;
     
     private String subject;
     private String senderAddress;
     private String recieverAddress;
     private String logFile;
     private String jndiLookup;
     private Boolean debugMode;
 
     public BufferedWriter out = null;
     
     
     public EmailHandler() {
          super();
          jndiLookup = "java:jboss/mail/Default";
          debugMode = false;
          logFile = "";
     }
     
     @Override
     public void publish(LogRecord record) {
    	  if(!isLoggable(record)){
    		  return;
    	  }
          if (!initialize()) {
               return;
          }
          process(record);
     }
 
     private synchronized boolean initialize() {
          if (out==null && logFile!=null && !logFile.equals("")) {
               FileWriter fstream = null;
               try {
                    fstream = new FileWriter(logFile,true);
                    out = new BufferedWriter(fstream);
               } catch (IOException e) {
                    reportError(e.getMessage(), e, ErrorManager.OPEN_FAILURE);
               }
               logToFile("Log file initialized. Logging to: " + logFile);
          }
          if(mailSession==null) {
               final Hashtable jndiProperties = new Hashtable();  
               jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
               Context context;
               String jndiNamespace = jndiLookup;
               if(debugMode) logToFile("Trying to initialize the mail session from jndi");
               try {
                    context = new InitialContext(jndiProperties);
                    if(debugMode) logToFile("Initial context was "+(context==null?"not found":"found"));
                    mailSession = (Session) context.lookup(jndiNamespace);
                    if(debugMode) logToFile("Mail session was "+(mailSession==null?"not found":"found"));
               } catch (NamingException e) {
                    String message = "There was an error initializing the mail session";
                    if(debugMode) logToFile(message + ": "+ e.getMessage());
                    reportError(message, e, ErrorManager.GENERIC_FAILURE);
                    return false;
               }  
          }
          return true;
     }
 
     private void process(LogRecord logRecord) {
          if(debugMode) logToFile("New mail should be sent");
          MimeMessage m = new MimeMessage(mailSession);
          if(debugMode) logToFile("New mail created");
          Address from;
          try {
               from = new InternetAddress(senderAddress);
               if(debugMode) logToFile("Sender address: " + senderAddress);
               Address[] to;
               if(recieverAddress.indexOf(",") == -1){
            	   to = new InternetAddress[] {new InternetAddress(recieverAddress) };
            	   if(debugMode) logToFile("Reciepient address: " + recieverAddress);
               }else{
            	   String[] emails = recieverAddress.split(",");
            	   to = new InternetAddress[emails.length];
            	   for(int i=0; i<emails.length; i++){
            		   to[i] = new InternetAddress(emails[i]);
            		   if(debugMode) logToFile("Reciepient address: " + emails[i]);
            	   }
               }
               m.setFrom(from);  
               m.setRecipients(Message.RecipientType.TO, to);  
               m.setSubject(subject);
               if(debugMode) logToFile("Subject: "+ subject);
               m.setSentDate(new java.util.Date());  
               m.setContent(getFormatter().format(logRecord),"text/plain");
               Transport.send(m);  
               if(debugMode) {
                    logToFile("Mail successfully sent");
               } else {
                    logToFile("Mail successfully sent to: "+ senderAddress);
               }
          } catch (AddressException e) {
               String message = "Could not resolve address";
               if(debugMode) logToFile(message + ": "+ e.getMessage());
               reportError(message, e, ErrorManager.GENERIC_FAILURE);
          } catch (MessagingException e) {
               String message = "Mail could not be sent due to";
               if(debugMode) logToFile(message + ": "+ e.getMessage());
               reportError(message, e, ErrorManager.GENERIC_FAILURE);
          }  
     }
 
     private void logToFile(String text) {
          try {
               if (out!=null) {
                    out.write((new Date()).toString() + "\t" + text+"\n");
                    out.flush();
               }
          } catch (IOException e) {
               reportError(e.getMessage(), e, ErrorManager.WRITE_FAILURE);
          }
          
     }
 
 
 
     @Override
     public void flush() {
          try {
               if (out!=null) {
                    out.flush();
               }
          } catch (IOException e) {
               reportError(e.getMessage(), e, ErrorManager.FLUSH_FAILURE);
          }
     }
 
 
     @Override
     public void close()     {
          if(out!=null) {
               try {
                    out.close();
               } catch (IOException e) {
                    reportError(e.getMessage(), e, ErrorManager.CLOSE_FAILURE);
               }
 
          }
     }
 
 
     public void setSubject(String subject) {
          this.subject = subject;
     }
 
     public void setSenderAddress(String senderAddress) {
          this.senderAddress = senderAddress;
     }
 
     public void setRecieverAddress(String recieverAddress) {
          this.recieverAddress = recieverAddress;
     }
 
     public void setLogFile(String logFile) {
          this.logFile = logFile;
     }
 
     public void setJndiLookup(String jndiLookup) {
          this.jndiLookup = jndiLookup;
     }
     
     public void setDebugMode(String debugMode) {
          this.debugMode = false;
          try {
               this.debugMode = Boolean.parseBoolean(debugMode);
          } catch (Exception e) {
          }
     }
}


将这个类打成jar包,放到$JBOSS_HOME/modules/com/jll/logger/main目录(这个目录不存在就需要自己去创建)

并在该目录下新建一个文件module.xml,内容如下

<?xml version="1.0" encoding="UTF-8"?> 
<module xmlns="urn:jboss:module:1.0" name="com.jll.loggers">
     <resources>    
           <resource-root path="EmailHandler.jar"/>
          <!-- Insert resources here --> 
     </resources>  
     <dependencies>    
          <module name="org.jboss.logging"/> 
          <module name="javax.api"/> 
          <module name="javax.mail.api"/>
		  <module name="org.jboss.remote-naming"/> 
     </dependencies>
</module> 


再找到jboss的配置文件standalone.xml或者是domail.xml

找到logger节点

<subsystem xmlns="urn:jboss:domain:logging:1.1">


加入如下内容

<custom-handler name="EmailAppender" class="com.jll.EmailHandler" module="com.jll.loggers">
                <level name="ERROR"/>
                <formatter>
                    <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
                </formatter>
                <properties>
                    <property name="jndiLookup" value="java:jboss/mail/Default"/>
                    <property name="subject" value="[SMTPAppender] Application message"/>
                    <property name="senderAddress" value="sender@qq.com"/>
                    <property name="recieverAddress" value="reciever@163.com"/> <!--这里如果要群发,用","隔开-->
                    <property name="logFile" value="D:\\temp\\logfile.txt"/>
                    <property name="debugMode" value="true"/>
                </properties>
 </custom-handler>


再在root-logger中加入

 <root-logger>
                <level name="INFO"/>
                <handlers>
                    <handler name="CONSOLE"/>
                    <handler name="FILE"/>
                    <handler name="EmailAppender"/>
                </handlers>
 </root-logger>


我在这里发送邮件时用到的是jboss定义的mail-session,为了以后配置方便

main-session定义如下:

<subsystem xmlns="urn:jboss:domain:mail:1.0">
            <mail-session jndi-name="java:jboss/mail/Default">
                <smtp-server outbound-socket-binding-ref="mail-smtp">
                    <login name="server@qq.com" password="password"/>
                </smtp-server>
            </mail-session>
</subsystem>

最后还有一处要配置的就是发送服务器的smtp

在最后的位置

 

<outbound-socket-binding name="mail-smtp">
            <remote-destination host="smtp.qq.com" port="25"/>
        </outbound-socket-binding>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值