package piv.zheng.log4j.test;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.ErrorCode;
import java.util.Properties;
import java.util.Date;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.Multipart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.AddressException;
public class SMTPAppender extends AppenderSkeleton {
private String to; //收件人
private String from; // 发件人
private String subject; //邮件标题
private String smtpHost; //邮件服务器
private String auth; //身份验证标识
private String username; //用户
private String password; //密码
private boolean locationInfo = false;
protected Session ses;
protected Message msg;
protected Properties props;
public SMTPAppender() {}
public SMTPAppender(Layout layout) {
this.layout = layout;
}
//应用设置
public void activateOptions() {
props = new Properties(System.getProperties());
if (smtpHost != null) {
props.put("mail.smtp.host", smtpHost);
}
if (auth != null) {
props.put("mail.smtp.auth", auth);
}
if (username != null) {
props.put("username", username);
}
if (password != null) {
props.put("password", password);
}
ses = Session.getInstance(props); //创建session
msg = new MimeMessage(ses); //创建message
try {
//为message设置发件人
if (from != null) {
msg.setFrom(getAddress(from));
} else {
msg.setFrom();
}
//为message设置收件人
if (to != null) {
msg.setRecipients(Message.RecipientType.TO, parseAddress(to));
}
//为message设置标题
if (subject != null) {
msg.setSubject(subject);
}
} catch (MessagingException e) {
LogLog.error("Could not activate SMTPAppender options.", e);
}
}
//重写执行方法,当执行日志输出时会被调用
public void append(LoggingEvent event) {
//检查message及layout
if (!checkEntryConditions()) {
return;
}
event.getThreadName();
event.getNDC();
if (locationInfo) {
event.getLocationInformation();
}
//发送邮件
sendBuffer(event);
}
protected boolean checkEntryConditions() {
if (this.msg == null) {
errorHandler.error("Message object not configured.");
return false;
}
if (this.layout == null) {
errorHandler.error("No layout set for appender named [" + name + "].");
return false;
}
return true;
}
synchronized public void close() {
this.closed = true;
}
InternetAddress getAddress(String addressStr) {
try {
return new InternetAddress(addressStr);
} catch (AddressException e) {
errorHandler.error("Could not parse address [" + addressStr + "].", e, ErrorCode.ADDRESS_PARSE_FAILURE);
return null;
}
}
InternetAddress[] parseAddress(String addressStr) {
try {
return InternetAddress.parse(addressStr, true);
} catch (AddressException e) {
errorHandler.error("Could not parse address [" + addressStr + "].", e, ErrorCode.ADDRESS_PARSE_FAILURE);
return null;
}
}
public boolean requiresLayout() {
return true;
}
//发送邮件
protected void sendBuffer(LoggingEvent event) {
try {
//将日志信息设置到message中
MimeBodyPart part = new MimeBodyPart();
StringBuffer sbuf = new StringBuffer();
String t = layout.getHeader();
if (t != null) {
sbuf.append(t);
}
sbuf.append(layout.format(event));
if (layout.ignoresThrowable()) {
String[] s = event.getThrowableStrRep();
if (s != null) {
for (int j = 0; j < s.length; j++) {
sbuf.append(s[j]);
}
}
}
t = layout.getFooter();
if (t != null) {
sbuf.append(t);
}
part.setContent(sbuf.toString(), layout.getContentType());
Multipart mp = new MimeMultipart();
mp.addBodyPart(part);
msg.setContent(mp); //为message设置内容,即日志信息
msg.setSentDate(new Date()); //为message设置发送时间
//发送邮件
Transport tr = ses.getTransport("smtp");
tr.connect(smtpHost, username, password);
tr.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
tr.close();
} catch (Exception e) {
LogLog.error("Error occured while sending e-mail notification.", e);
}
}
public void setTo(String to) {
this.to = to;
}
public String getTo() {
return to;
}
public void setFrom(String from) {
this.from = from;
}
public String getFrom() {
return from;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setSMTPHost(String smtpHost) {
this.smtpHost = smtpHost;
}
public String getSMTPHost() {
return smtpHost;
}
public void setAuth(String auth) {
this.auth = auth;
}
public String getAuth() {
return auth;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public void setLocationInfo(boolean locationInfo) {
this.locationInfo = locationInfo;
}
public boolean getLocationInfo() {
return locationInfo;
}
}
查看本文来源