001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017
018package org.apache.logging.log4j.core.appender;
019
020import java.io.Serializable;
021
022import org.apache.logging.log4j.core.Appender;
023import org.apache.logging.log4j.core.Core;
024import org.apache.logging.log4j.core.Filter;
025import org.apache.logging.log4j.core.Layout;
026import org.apache.logging.log4j.core.LogEvent;
027import org.apache.logging.log4j.core.config.Configuration;
028import org.apache.logging.log4j.core.config.DefaultConfiguration;
029import org.apache.logging.log4j.core.config.plugins.Plugin;
030import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
031import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
032import org.apache.logging.log4j.core.config.plugins.PluginElement;
033import org.apache.logging.log4j.core.config.plugins.PluginFactory;
034import org.apache.logging.log4j.core.config.plugins.validation.constraints.Required;
035import org.apache.logging.log4j.core.config.plugins.validation.constraints.ValidPort;
036import org.apache.logging.log4j.core.filter.ThresholdFilter;
037import org.apache.logging.log4j.core.layout.HtmlLayout;
038import org.apache.logging.log4j.core.net.SmtpManager;
039import org.apache.logging.log4j.core.util.Booleans;
040
041/**
042 * Send an e-mail when a specific logging event occurs, typically on errors or
043 * fatal errors.
044 *
045 * <p>
046 * The number of logging events delivered in this e-mail depend on the value of
047 * <b>BufferSize</b> option. The <code>SmtpAppender</code> keeps only the last
048 * <code>BufferSize</code> logging events in its cyclic buffer. This keeps
049 * memory requirements at a reasonable level while still delivering useful
050 * application context.
051 *
052 * By default, an email message will formatted as HTML. This can be modified by
053 * setting a layout for the appender.
054 *
055 * By default, an email message will be sent when an ERROR or higher severity
056 * message is appended. This can be modified by setting a filter for the
057 * appender.
058 */
059@Plugin(name = "SMTP", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE, printObject = true)
060public final class SmtpAppender extends AbstractAppender {
061
062    private static final int DEFAULT_BUFFER_SIZE = 512;
063
064    /** The SMTP Manager */
065    private final SmtpManager manager;
066
067    private SmtpAppender(final String name, final Filter filter, final Layout<? extends Serializable> layout, final SmtpManager manager,
068                         final boolean ignoreExceptions) {
069        super(name, filter, layout, ignoreExceptions);
070        this.manager = manager;
071    }
072
073    /**
074     * Create a SmtpAppender.
075     *
076     * @param name
077     *            The name of the Appender.
078     * @param to
079     *            The comma-separated list of recipient email addresses.
080     * @param cc
081     *            The comma-separated list of CC email addresses.
082     * @param bcc
083     *            The comma-separated list of BCC email addresses.
084     * @param from
085     *            The email address of the sender.
086     * @param replyTo
087     *            The comma-separated list of reply-to email addresses.
088     * @param subject The subject of the email message.
089     * @param smtpProtocol The SMTP transport protocol (such as "smtps", defaults to "smtp").
090     * @param smtpHost
091     *            The SMTP hostname to send to.
092     * @param smtpPortStr
093     *            The SMTP port to send to.
094     * @param smtpUsername
095     *            The username required to authenticate against the SMTP server.
096     * @param smtpPassword
097     *            The password required to authenticate against the SMTP server.
098     * @param smtpDebug
099     *            Enable mail session debuging on STDOUT.
100     * @param bufferSizeStr
101     *            How many log events should be buffered for inclusion in the
102     *            message?
103     * @param layout
104     *            The layout to use (defaults to HtmlLayout).
105     * @param filter
106     *            The Filter or null (defaults to ThresholdFilter, level of
107     *            ERROR).
108     * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
109     *               they are propagated to the caller.
110     * @return The SmtpAppender.
111     */
112    @PluginFactory
113    public static SmtpAppender createAppender(
114            @PluginConfiguration final Configuration config,
115            @PluginAttribute("name") @Required final String name,
116            @PluginAttribute("to") final String to,
117            @PluginAttribute("cc") final String cc,
118            @PluginAttribute("bcc") final String bcc,
119            @PluginAttribute("from") final String from,
120            @PluginAttribute("replyTo") final String replyTo,
121            @PluginAttribute("subject") final String subject,
122            @PluginAttribute("smtpProtocol") final String smtpProtocol,
123            @PluginAttribute("smtpHost") final String smtpHost,
124            @PluginAttribute(value = "smtpPort", defaultString = "0") @ValidPort final String smtpPortStr,
125            @PluginAttribute("smtpUsername") final String smtpUsername,
126            @PluginAttribute(value = "smtpPassword", sensitive = true) final String smtpPassword,
127            @PluginAttribute("smtpDebug") final String smtpDebug,
128            @PluginAttribute("bufferSize") final String bufferSizeStr,
129            @PluginElement("Layout") Layout<? extends Serializable> layout,
130            @PluginElement("Filter") Filter filter,
131            @PluginAttribute("ignoreExceptions") final String ignore) {
132        if (name == null) {
133            LOGGER.error("No name provided for SmtpAppender");
134            return null;
135        }
136
137        final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
138        final int smtpPort = AbstractAppender.parseInt(smtpPortStr, 0);
139        final boolean isSmtpDebug = Boolean.parseBoolean(smtpDebug);
140        final int bufferSize = bufferSizeStr == null ? DEFAULT_BUFFER_SIZE : Integer.parseInt(bufferSizeStr);
141
142        if (layout == null) {
143            layout = HtmlLayout.createDefaultLayout();
144        }
145        if (filter == null) {
146            filter = ThresholdFilter.createFilter(null, null, null);
147        }
148        final Configuration configuration = config != null ? config : new DefaultConfiguration();
149
150        final SmtpManager manager = SmtpManager.getSmtpManager(configuration, to, cc, bcc, from, replyTo, subject, smtpProtocol,
151            smtpHost, smtpPort, smtpUsername, smtpPassword, isSmtpDebug, filter.toString(),  bufferSize);
152        if (manager == null) {
153            return null;
154        }
155
156        return new SmtpAppender(name, filter, layout, manager, ignoreExceptions);
157    }
158
159    /**
160     * Capture all events in CyclicBuffer.
161     * @param event The Log event.
162     * @return true if the event should be filtered.
163     */
164    @Override
165    public boolean isFiltered(final LogEvent event) {
166        final boolean filtered = super.isFiltered(event);
167        if (filtered) {
168            manager.add(event);
169        }
170        return filtered;
171    }
172
173    /**
174     * Perform SmtpAppender specific appending actions, mainly adding the event
175     * to a cyclic buffer and checking if the event triggers an e-mail to be
176     * sent.
177     * @param event The Log event.
178     */
179    @Override
180    public void append(final LogEvent event) {
181        manager.sendEvents(getLayout(), event);
182    }
183}