svn commit: r566 - in logback/trunk: logback-classic logback-classic/src/main/java/ch/qos/logback/classic/net logback-classic/src/test/java/ch/qos/logback/classic/net logback-core logback-core/src/main/java/ch/qos/logback/core/net

Author: seb Date: Tue Sep 12 17:20:42 2006 New Revision: 566 Added: logback/trunk/logback-core/src/main/java/ch/qos/logback/core/net/SMTPAppenderBase.java Modified: logback/trunk/logback-classic/pom.xml logback/trunk/logback-classic/src/main/java/ch/qos/logback/classic/net/SMTPAppender.java logback/trunk/logback-classic/src/test/java/ch/qos/logback/classic/net/SMTPAppenderTest.java logback/trunk/logback-core/pom.xml Log: - added a SMTPAppenderBase class in logback core - modified SMTPAppender accordingly - updated tests - updated pom.xml files Modified: logback/trunk/logback-classic/pom.xml ============================================================================== --- logback/trunk/logback-classic/pom.xml (original) +++ logback/trunk/logback-classic/pom.xml Tue Sep 12 17:20:42 2006 @@ -36,12 +36,6 @@ <artifactId>logback-core</artifactId> <scope>compile</scope> </dependency> - - <dependency> - <groupId>javax.mail</groupId> - <artifactId>mail</artifactId> - <scope>compile</scope> - </dependency> <dependency> <groupId>dom4j</groupId> @@ -50,6 +44,12 @@ </dependency> <dependency> + <groupId>javax.mail</groupId> + <artifactId>mail</artifactId> + <scope>test</scope> + </dependency> + + <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <classifier>tests</classifier> Modified: logback/trunk/logback-classic/src/main/java/ch/qos/logback/classic/net/SMTPAppender.java ============================================================================== --- logback/trunk/logback-classic/src/main/java/ch/qos/logback/classic/net/SMTPAppender.java (original) +++ logback/trunk/logback-classic/src/main/java/ch/qos/logback/classic/net/SMTPAppender.java Tue Sep 12 17:20:42 2006 @@ -11,27 +11,12 @@ package ch.qos.logback.classic.net; import java.io.File; -import java.util.Date; -import java.util.Properties; - -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.Session; -import javax.mail.Transport; -import javax.mail.internet.AddressException; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeMultipart; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.helpers.CyclicBuffer; import ch.qos.logback.classic.spi.LoggingEvent; -import ch.qos.logback.core.AppenderBase; -import ch.qos.logback.core.Layout; +import ch.qos.logback.core.net.SMTPAppenderBase; import ch.qos.logback.core.rolling.TriggeringPolicy; -import ch.qos.logback.core.util.OptionHelper; /** * Send an e-mail when a specific logging event occurs, typically on errors or @@ -47,22 +32,11 @@ * @author Ceki Gülcü * @author Sébastien Pennec * - * @since 1.0 */ -public class SMTPAppender extends AppenderBase { - private Layout layout; +public class SMTPAppender extends SMTPAppenderBase { - private String to; - private String from; - private String subject; - private String smtpHost; private int bufferSize = 512; - private boolean locationInfo = false; - protected CyclicBuffer cb = new CyclicBuffer(bufferSize); - protected Message msg; - - protected TriggeringPolicy evaluator; /** * The default constructor will instantiate the appender with a @@ -82,194 +56,33 @@ } /** - * Start the appender - */ - public void start() { - Properties props = new Properties(System.getProperties()); - if (smtpHost != null) { - props.put("mail.smtp.host", smtpHost); - } - - Session session = Session.getInstance(props, null); - // session.setDebug(true); - msg = new MimeMessage(session); - - try { - if (from != null) { - msg.setFrom(getAddress(from)); - } else { - msg.setFrom(); - } - - msg.setRecipients(Message.RecipientType.TO, parseAddress(to)); - if (subject != null) { - msg.setSubject(subject); - } - - started = true; - - } catch (MessagingException e) { - addError("Could not activate SMTPAppender options.", e); - } - } - - /** * Perform SMTPAppender specific appending actions, mainly adding the event to - * a cyclic buffer and checking if the event triggers an e-mail to be sent. + * a cyclic buffer. */ - protected void append(Object eventObject) { + protected void subAppend(Object eventObject) { LoggingEvent event = (LoggingEvent) eventObject; - if (!checkEntryConditions()) { - return; - } - event.getThreadName(); - // if (locationInfo) { - // event.getLocationInformation(); - // } cb.add(event); // addInfo("Added event to the cyclic buffer: " + event.getMessage()); - - if (evaluator.isTriggeringEvent(null, event)) { - sendBuffer(); - } } - /** - * This method determines if there is a sense in attempting to append. - * - * <p> - * It checks whether there is a set output target and also if there is a set - * layout. If these checks fail, then the boolean value <code>false</code> - * is returned. - */ - protected boolean checkEntryConditions() { - if (this.msg == null) { - addError("Message object not configured."); - return false; - } - - if (this.evaluator == null) { - addError("No TriggeringPolicy is set for appender [" + name + "]."); - return false; + @Override + protected void fillBuffer(StringBuffer sbuf) { + int len = cb.length(); + for (int i = 0; i < len; i++) { + // sbuf.append(MimeUtility.encodeText(layout.format(cb.get()))); + LoggingEvent event = cb.get(); + sbuf.append(layout.doLayout(event)); + // if (layout.ignoresThrowable()) { + // String[] s = event.getThrowableStrRep(); + // if (s != null) { + // for (int j = 0; j < s.length; j++) { + // sbuf.append(s[j]); + // } + // } + // } } - - if (this.layout == null) { - addError("No layout set for appender named [" + name + "]."); - return false; - } - return true; - } - - synchronized public void stop() { - this.started = false; - } - - InternetAddress getAddress(String addressStr) { - try { - return new InternetAddress(addressStr); - } catch (AddressException e) { - addError("Could not parse address [" + addressStr + "].", e); - return null; - } - } - - InternetAddress[] parseAddress(String addressStr) { - try { - return InternetAddress.parse(addressStr, true); - } catch (AddressException e) { - addError("Could not parse address [" + addressStr + "].", e); - return null; - } - } - - /** - * Returns value of the <b>To</b> option. - */ - public String getTo() { - return to; - } - - /** - * Send the contents of the cyclic buffer as an e-mail message. - */ - protected void sendBuffer() { - - // Note: this code already owns the monitor for this - // appender. This frees us from needing to synchronize on 'cb'. - try { - MimeBodyPart part = new MimeBodyPart(); - - StringBuffer sbuf = new StringBuffer(); - String t = layout.getHeader(); - if (t != null) - sbuf.append(t); - int len = cb.length(); - for (int i = 0; i < len; i++) { - // sbuf.append(MimeUtility.encodeText(layout.format(cb.get()))); - LoggingEvent event = cb.get(); - sbuf.append(layout.doLayout(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(), "text/plain"); - - Multipart mp = new MimeMultipart(); - mp.addBodyPart(part); - msg.setContent(mp); - - msg.setSentDate(new Date()); - Transport.send(msg); - } catch (Exception e) { - addError("Error occured while sending e-mail notification.", e); - } - } - - /** - * Returns value of the <b>EvaluatorClass</b> option. - */ - public String getEvaluatorClass() { - return evaluator == null ? null : evaluator.getClass().getName(); - } - - /** - * Returns value of the <b>From</b> option. - */ - public String getFrom() { - return from; - } - - /** - * Returns value of the <b>Subject</b> option. - */ - public String getSubject() { - return subject; - } - - /** - * The <b>From</b> option takes a string value which should be a e-mail - * address of the sender. - */ - public void setFrom(String from) { - this.from = from; - } - - /** - * The <b>Subject</b> option takes a string value which should be a the - * subject of the e-mail message. - */ - public void setSubject(String subject) { - this.subject = subject; } /** @@ -285,79 +98,11 @@ } /** - * The <b>SMTPHost</b> option takes a string value which should be a the host - * name of the SMTP server that will send the e-mail message. - */ - public void setSMTPHost(String smtpHost) { - this.smtpHost = smtpHost; - } - - /** - * Returns value of the <b>SMTPHost</b> option. - */ - public String getSMTPHost() { - return smtpHost; - } - - /** - * The <b>To</b> option takes a string value which should be a comma - * separated list of e-mail address of the recipients. - */ - public void setTo(String to) { - this.to = to; - } - - /** * Returns value of the <b>BufferSize</b> option. */ public int getBufferSize() { return bufferSize; } - - /** - * The <b>EvaluatorClass</b> option takes a string value representing the - * name of the class implementing the {@link TriggeringEventEvaluator} - * interface. A corresponding object will be instantiated and assigned as the - * triggering event evaluator for the SMTPAppender. - */ - public void setEvaluatorClass(String value) { - try { - evaluator = (TriggeringPolicy) OptionHelper.instantiateByClassName(value, - TriggeringPolicy.class); - } catch (Exception ex) { - addError("Evaluator class instanciation failed"); - } - } - - /** - * The <b>LocationInfo</b> option takes a boolean value. By default, it is - * set to false which means there will be no effort to extract the location - * information related to the event. As a result, the layout that formats the - * events as they are sent out in an e-mail is likely to place the wrong - * location information (if present in the format). - * - * <p> - * Location information extraction is comparatively very slow and should be - * avoided unless performance is not a concern. - */ - public void setLocationInfo(boolean locationInfo) { - this.locationInfo = locationInfo; - } - - /** - * Returns value of the <b>LocationInfo</b> option. - */ - public boolean getLocationInfo() { - return locationInfo; - } - - public Layout getLayout() { - return layout; - } - - public void setLayout(Layout layout) { - this.layout = layout; - } } class DefaultEvaluator implements TriggeringPolicy { Modified: logback/trunk/logback-classic/src/test/java/ch/qos/logback/classic/net/SMTPAppenderTest.java ============================================================================== --- logback/trunk/logback-classic/src/test/java/ch/qos/logback/classic/net/SMTPAppenderTest.java (original) +++ logback/trunk/logback-classic/src/test/java/ch/qos/logback/classic/net/SMTPAppenderTest.java Tue Sep 12 17:20:42 2006 @@ -12,102 +12,101 @@ public class SMTPAppenderTest extends TestCase { - SMTPAppender appender; + SMTPAppender appender; - public void setUp() throws Exception { - super.setUp(); - LoggerContext lc = new LoggerContext(); - appender = new SMTPAppender(); - appender.setContext(lc); - appender.setName("smtp"); - appender.setFrom("user@host.dom"); - appender.setLayout(buildLayout(lc)); - appender.setSMTPHost("mail2.qos.ch"); - appender.setSubject("logging report"); - appender.setTo("sebastien.nospam@qos.ch"); - appender.start(); - } - - public void tearDown() throws Exception { - super.tearDown(); - appender = null; - } - - public void testStart() { - try { - Address[] addressArray = appender.msg.getFrom(); - Address address = addressArray[0]; - assertEquals("user@host.dom", address.toString()); - - addressArray = null; - address = null; - - addressArray = appender.msg.getAllRecipients(); - address = addressArray[0]; - assertEquals("sebastien.nospam@qos.ch", address.toString()); - - assertEquals("logging report", appender.msg.getSubject()); - - assertTrue(appender.isStarted()); - - } catch (MessagingException ex) { - fail("Unexpected exception."); - } - } - - public void testAppendNonTriggeringEvent() { - LoggingEvent event = new LoggingEvent(); - event.setThreadName("thead name"); - event.setLevel(Level.DEBUG); - appender.append(event); - assertEquals(1, appender.cb.length()); - } - - public void testEntryConditionsCheck() { - appender.checkEntryConditions(); - assertEquals(0, appender.getContext().getStatusManager().getCount()); - } - - public void testEntryConditionsCheckNoMessage() { - appender.msg = null; - appender.checkEntryConditions(); - assertEquals(1, appender.getContext().getStatusManager().getCount()); - } - - public void testEntryConditionsCheckNoEvaluator() { - appender.evaluator = null; - appender.checkEntryConditions(); - assertEquals(1, appender.getContext().getStatusManager().getCount()); - } - - public void testEntryConditionsCheckNoLayout() { - appender.setLayout(null); - appender.checkEntryConditions(); - assertEquals(1, appender.getContext().getStatusManager().getCount()); - } - - - public void testDefaultEvaluatorNoTrigger() { - DefaultEvaluator evaluator = new DefaultEvaluator(); - LoggingEvent le = new LoggingEvent(); - le.setLevel(Level.DEBUG); - assertFalse(evaluator.isTriggeringEvent(null,le)); - } - - public void testDefaultEvaluatorTrigger() { - DefaultEvaluator evaluator = new DefaultEvaluator(); - LoggingEvent le = new LoggingEvent(); - le.setLevel(Level.ERROR); - assertTrue(evaluator.isTriggeringEvent(null,le)); - } - - private static Layout buildLayout(LoggerContext lc) { - PatternLayout layout = new PatternLayout(); - layout.setContext(lc); - layout.setHeader("Some header\n"); - layout.setPattern("%-4relative [%thread] %-5level %class - %msg%n"); - layout.setFooter("Some footer"); - layout.start(); - return layout; - } + public void setUp() throws Exception { + super.setUp(); + LoggerContext lc = new LoggerContext(); + appender = new SMTPAppender(); + appender.setContext(lc); + appender.setName("smtp"); + appender.setFrom("user@host.dom"); + appender.setLayout(buildLayout(lc)); + appender.setSMTPHost("mail2.qos.ch"); + appender.setSubject("logging report"); + appender.setTo("sebastien.nospam@qos.ch"); + appender.start(); + } + + public void tearDown() throws Exception { + super.tearDown(); + appender = null; + } + + public void testStart() { + try { + Address[] addressArray = appender.getMessage().getFrom(); + Address address = addressArray[0]; + assertEquals("user@host.dom", address.toString()); + + addressArray = null; + address = null; + + addressArray = appender.getMessage().getAllRecipients(); + address = addressArray[0]; + assertEquals("sebastien.nospam@qos.ch", address.toString()); + + assertEquals("logging report", appender.getMessage().getSubject()); + + assertTrue(appender.isStarted()); + + } catch (MessagingException ex) { + fail("Unexpected exception."); + } + } + + public void testAppendNonTriggeringEvent() { + LoggingEvent event = new LoggingEvent(); + event.setThreadName("thead name"); + event.setLevel(Level.DEBUG); + appender.subAppend(event); + assertEquals(1, appender.cb.length()); + } + + public void testEntryConditionsCheck() { + appender.checkEntryConditions(); + assertEquals(0, appender.getContext().getStatusManager().getCount()); + } + + public void testEntryConditionsCheckNoMessage() { + appender.setMessage(null); + appender.checkEntryConditions(); + assertEquals(1, appender.getContext().getStatusManager().getCount()); + } + + public void testEntryConditionsCheckNoEvaluator() { + appender.setEvaluator(null); + appender.checkEntryConditions(); + assertEquals(1, appender.getContext().getStatusManager().getCount()); + } + + public void testEntryConditionsCheckNoLayout() { + appender.setLayout(null); + appender.checkEntryConditions(); + assertEquals(1, appender.getContext().getStatusManager().getCount()); + } + + public void testDefaultEvaluatorNoTrigger() { + DefaultEvaluator evaluator = new DefaultEvaluator(); + LoggingEvent le = new LoggingEvent(); + le.setLevel(Level.DEBUG); + assertFalse(evaluator.isTriggeringEvent(null, le)); + } + + public void testDefaultEvaluatorTrigger() { + DefaultEvaluator evaluator = new DefaultEvaluator(); + LoggingEvent le = new LoggingEvent(); + le.setLevel(Level.ERROR); + assertTrue(evaluator.isTriggeringEvent(null, le)); + } + + private static Layout buildLayout(LoggerContext lc) { + PatternLayout layout = new PatternLayout(); + layout.setContext(lc); + layout.setHeader("Some header\n"); + layout.setPattern("%-4relative [%thread] %-5level %class - %msg%n"); + layout.setFooter("Some footer"); + layout.start(); + return layout; + } } Modified: logback/trunk/logback-core/pom.xml ============================================================================== --- logback/trunk/logback-core/pom.xml (original) +++ logback/trunk/logback-core/pom.xml Tue Sep 12 17:20:42 2006 @@ -35,6 +35,11 @@ <groupId>janino</groupId> <artifactId>janino</artifactId> </dependency> + <dependency> + <groupId>javax.mail</groupId> + <artifactId>mail</artifactId> + <scope>compile</scope> + </dependency> </dependencies> Added: logback/trunk/logback-core/src/main/java/ch/qos/logback/core/net/SMTPAppenderBase.java ============================================================================== --- (empty file) +++ logback/trunk/logback-core/src/main/java/ch/qos/logback/core/net/SMTPAppenderBase.java Tue Sep 12 17:20:42 2006 @@ -0,0 +1,285 @@ +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * + * Copyright (C) 1999-2006, QOS.ch + * + * This library is free software, you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation. + */ + +package ch.qos.logback.core.net; + +import java.util.Date; +import java.util.Properties; + +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.Multipart; +import javax.mail.Session; +import javax.mail.Transport; +import javax.mail.internet.AddressException; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeMultipart; + +import ch.qos.logback.core.AppenderBase; +import ch.qos.logback.core.Layout; +import ch.qos.logback.core.rolling.TriggeringPolicy; +import ch.qos.logback.core.util.OptionHelper; + +/** + * An abstract class that provides basic support for + * sending events to an email address. + * + * @author Ceki Gülcü + * @author Sébastien Pennec + * + */ +public abstract class SMTPAppenderBase extends AppenderBase { + protected Layout layout; + + private String to; + private String from; + private String subject; + private String smtpHost; + + protected Message msg; + + protected TriggeringPolicy evaluator; + + /** + * Start the appender + */ + public void start() { + Properties props = new Properties(System.getProperties()); + if (smtpHost != null) { + props.put("mail.smtp.host", smtpHost); + } + + Session session = Session.getInstance(props, null); + // session.setDebug(true); + msg = new MimeMessage(session); + + try { + if (from != null) { + msg.setFrom(getAddress(from)); + } else { + msg.setFrom(); + } + + msg.setRecipients(Message.RecipientType.TO, parseAddress(to)); + if (subject != null) { + msg.setSubject(subject); + } + + started = true; + + } catch (MessagingException e) { + addError("Could not activate SMTPAppender options.", e); + } + } + + /** + * Perform SMTPAppender specific appending actions, delegating some + * of them to a subclass and checking if the event triggers an e-mail to be sent. + */ + protected void append(Object eventObject) { + + if (!checkEntryConditions()) { + return; + } + + subAppend(eventObject); + + if (evaluator.isTriggeringEvent(null, eventObject)) { + sendBuffer(); + } + } + + abstract protected void subAppend(Object eventObject); + + /** + * This method determines if there is a sense in attempting to append. + * + * <p> + * It checks whether there is a set output target and also if there is a set + * layout. If these checks fail, then the boolean value <code>false</code> + * is returned. + */ + public boolean checkEntryConditions() { + if (this.msg == null) { + addError("Message object not configured."); + return false; + } + + if (this.evaluator == null) { + addError("No TriggeringPolicy is set for appender [" + name + "]."); + return false; + } + + if (this.layout == null) { + addError("No layout set for appender named [" + name + "]."); + return false; + } + return true; + } + + synchronized public void stop() { + this.started = false; + } + + InternetAddress getAddress(String addressStr) { + try { + return new InternetAddress(addressStr); + } catch (AddressException e) { + addError("Could not parse address [" + addressStr + "].", e); + return null; + } + } + + InternetAddress[] parseAddress(String addressStr) { + try { + return InternetAddress.parse(addressStr, true); + } catch (AddressException e) { + addError("Could not parse address [" + addressStr + "].", e); + return null; + } + } + + /** + * Returns value of the <b>To</b> option. + */ + public String getTo() { + return to; + } + + /** + * Send the contents of the cyclic buffer as an e-mail message. + */ + protected void sendBuffer() { + + // Note: this code already owns the monitor for this + // appender. This frees us from needing to synchronize on 'cb'. + try { + MimeBodyPart part = new MimeBodyPart(); + + StringBuffer sbuf = new StringBuffer(); + String t = layout.getHeader(); + fillBuffer(sbuf); + t = layout.getFooter(); + if (t != null) + sbuf.append(t); + part.setContent(sbuf.toString(), "text/plain"); + + Multipart mp = new MimeMultipart(); + mp.addBodyPart(part); + msg.setContent(mp); + + msg.setSentDate(new Date()); + Transport.send(msg); + } catch (Exception e) { + addError("Error occured while sending e-mail notification.", e); + } + } + + abstract protected void fillBuffer(StringBuffer sbuf); + + /** + * Returns value of the <b>EvaluatorClass</b> option. + */ + public String getEvaluatorClass() { + return evaluator == null ? null : evaluator.getClass().getName(); + } + + /** + * Returns value of the <b>From</b> option. + */ + public String getFrom() { + return from; + } + + /** + * Returns value of the <b>Subject</b> option. + */ + public String getSubject() { + return subject; + } + + /** + * The <b>From</b> option takes a string value which should be a e-mail + * address of the sender. + */ + public void setFrom(String from) { + this.from = from; + } + + /** + * The <b>Subject</b> option takes a string value which should be a the + * subject of the e-mail message. + */ + public void setSubject(String subject) { + this.subject = subject; + } + + /** + * The <b>SMTPHost</b> option takes a string value which should be a the host + * name of the SMTP server that will send the e-mail message. + */ + public void setSMTPHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + /** + * Returns value of the <b>SMTPHost</b> option. + */ + public String getSMTPHost() { + return smtpHost; + } + + /** + * The <b>To</b> option takes a string value which should be a comma + * separated list of e-mail address of the recipients. + */ + public void setTo(String to) { + this.to = to; + } + + //for testing purpose only + public Message getMessage() { + return msg; + } + + //for testing purpose only + public void setMessage(Message msg) { + this.msg = msg; + } + + public void setEvaluator(TriggeringPolicy evaluator) { + this.evaluator = evaluator; + } + + /** + * The <b>EvaluatorClass</b> option takes a string value representing the + * name of the class implementing the {@link TriggeringEventEvaluator} + * interface. A corresponding object will be instantiated and assigned as the + * triggering event evaluator for the SMTPAppender. + */ + public void setEvaluatorClass(String value) { + try { + evaluator = (TriggeringPolicy) OptionHelper.instantiateByClassName(value, + TriggeringPolicy.class); + } catch (Exception ex) { + addError("Evaluator class instanciation failed"); + } + } + + public Layout getLayout() { + return layout; + } + + public void setLayout(Layout layout) { + this.layout = layout; + } +}
participants (1)
-
noreply.seb@qos.ch