我用的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="[email protected]"/>
<property name="recieverAddress" value="[email protected]"/> <!--這裏如果要羣發,用","隔開-->
<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="[email protected]" 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>