This Handler will store a fixed number of log records used to generate a single email message. When the internal buffer reaches capacity, all log records are formatted and placed in an email which is sent to an email server. The code to manually setup this handler can be as simple as the following:
Properties props = new Properties();
props.put("mail.smtp.host", "my-mail-server");
props.put("mail.to", "[email protected]");
props.put("verify", "local");
MailHandler h = new MailHandler(props);
h.setLevel(Level.WARNING);
Configuration: The LogManager should define at least one or more recipient addresses and a mail host for outgoing email. The code to setup this handler via the logging properties can be as simple as the following:
#Default MailHandler settings.
com.sun.mail.util.logging.MailHandler.mail.smtp.host = my-mail-server
com.sun.mail.util.logging.MailHandler.mail.to = [email protected]
com.sun.mail.util.logging.MailHandler.level = WARNING
com.sun.mail.util.logging.MailHandler.verify = local
For a custom handler, e.g. com.foo.MyHandler, the properties would
be:
#Subclass com.foo.MyHandler settings.
com.foo.MyHandler.mail.smtp.host = my-mail-server
com.foo.MyHandler.mail.to = [email protected]
com.foo.MyHandler.level = WARNING
com.foo.MyHandler.verify = local
All mail properties documented in the Java Mail API cascade to the
LogManager by prefixing a key using the fully qualified class name of this
MailHandler or the fully qualified derived class name dot mail
property. If the prefixed property is not found, then the mail property
itself is searched in the LogManager. By default each MailHandler is
initialized using the following LogManager configuration properties where
<handler-name> refers to the fully qualified class name of the
handler. If properties are not defined, or contain invalid values, then the
specified default values are used.
Normalization: The error manager, filters, and formatters when loaded from the LogManager are converted into canonical form inside the MailHandler. The pool of interned values is limited to each MailHandler object such that no two MailHandler objects created by the LogManager will be created sharing identical error managers, filters, or formatters. If a filter or formatter should not be interned then it is recommended to retain the identity equals and identity hashCode methods as the implementation. For a filter or formatter to be interned the class must implement the equals and hashCode methods. The recommended code to use for stateless filters and formatters is:
public boolean equals(Object obj) {
return obj == null ? false : obj.getClass() == getClass();
}
public int hashCode() {
return 31 * getClass().hashCode();
}
Sorting: All LogRecord objects are ordered prior to formatting if this Handler has a non null comparator. Developers might be interested in sorting the formatted email by thread id, time, and sequence properties of a LogRecord. Where as system administrators might be interested in sorting the formatted email by thrown, level, time, and sequence properties of a LogRecord. If comparator for this handler is null then the order is unspecified.
Formatting: The main message body is formatted using the Formatter returned by getFormatter(). Only records that pass the filter returned by getFilter() will be included in the message body. The subject Formatter will see all LogRecord objects that were published regardless of the current Filter. The MIME type of the message body can be overridden by adding a MIME entry using the simple class name of the body formatter as the file extension. The MIME type of the attachments can be overridden by changing the attachment file name extension or by editing the default MIME entry for a specific file name extension.
Attachments: This Handler allows multiple attachments per each email message. The presence of an attachment formatter will change the content type of the email message to a multi-part message. The attachment order maps directly to the array index order in this Handler with zero index being the first attachment. The number of attachment formatters controls the number of attachments per email and the content type of each attachment. The attachment filters determine if a LogRecord will be included in an attachment. If an attachment filter is null then all records are included for that attachment. Attachments without content will be omitted from email message. The attachment name formatters create the file name for an attachment. Custom attachment name formatters can be used to generate an attachment name based on the contents of the attachment.
Push Level and Push Filter: The push method, push level, and optional push filter can be used to conditionally trigger a push at or prior to full capacity. When a push occurs, the current buffer is formatted into an email and is sent to the email server. If the push method, push level, or push filter trigger a push then the outgoing email is flagged as high importance with urgent priority.
Buffering: Log records that are published are stored in an internal buffer. When this buffer reaches capacity the existing records are formatted and sent in an email. Any published records can be sent before reaching capacity by explictly calling the flush, push, or close methods. If a circular buffer is required then this handler can be wrapped with a java.util.logging.MemoryHandler typically with an equivalent capacity, level, and push level.
Error Handling: If the transport of an email message fails, the email is converted to a raw string and is then passed as the msg parameter to reportError along with the exception describing the cause of the failure. This allows custom error managers to store, reconstruct, and resend the original MimeMessage. The message parameter string is not a raw email if it starts with value returned from Level.SEVERE.getName(). Custom error managers can use the following test to determine if the msg parameter from this handler is a raw email:
public void error(String msg, Exception ex, int code) {
if (msg == null || msg.length() == 0 || msg.startsWith(Level.SEVERE.getName())) {
super.error(msg, ex, code);
} else {
//The 'msg' parameter is a raw email.
}
}
| Modifier and Type | Class and Description |
|---|---|
| private static class | MailHandler.DefaultAuthenticator
Used for storing a password from the LogManager or literal string. |
| private static class | MailHandler.GetAndSetContext
Performs a get and set of the context class loader with privileges enabled. |
| private static class | MailHandler.TailNameFormatter
Used for naming attachment file names and the main subject line. |
| Modifier and Type | Field and Description |
|---|---|
| private volatile Filter[] | attachmentFilters
Holds the filters for each attachment. |
| private Formatter[] | attachmentFormatters
Holds the formatters that create the content for each attachment. |
| private Formatter[] | attachmentNames
Holds the formatters that create the file name for each attachment. |
| private Authenticator | auth
Holds the authenticator required to login to the email server. |
| private int | capacity
The maximum number of log records to format per email. |
| private Comparator | comparator
Used to order all log records prior to formatting. |
| private FileTypeMap | contentTypes
Used to override the content type for the body and set the content type for each attachment. |
| private LogRecord[] | data
Holds all of the log records that will be used to create the email. |
| private static final Filter[] | EMPTY_FILTERS
Use the emptyFilterArray method. |
| private static final Formatter[] | EMPTY_FORMATTERS
Use the emptyFormatterArray method. |
| private String | encoding
Holds the encoding name for this handler.
|
| private volatile ErrorManager | errorManager
Holds the error manager for this handler.
|
| private volatile Filter | filter
Holds the entry and body filter for this handler.
|
| private Formatter | formatter
Holds the entry and body filter for this handler.
|
| private boolean | isWriting
Determines if we are inside of a push. |
| private volatile Level | logLevel
Holds the level for this handler.
|
| private static final PrivilegedAction | MAILHANDLER_LOADER
The action to set the context class loader for use with the JavaMail API. |
| private Properties | mailProps
Holds all of the email server properties. |
| private int[] | matched
A mapping of log record to matching filter index. |
| private static final int | MIN_HEADER_SIZE
Min byte size for header data. |
| private static final ThreadLocal | MUTEX
A thread local mutex used to prevent logging loops. |
| private static final Integer | MUTEX_LINKAGE
The used for linkage error reporting. |
| private static final Integer | MUTEX_PUBLISH
The marker object used to report a publishing state. |
| private static final Integer | MUTEX_REPORT
The used for the error reporting state. |
| private static final int | offValue
Cache the off value.
|
| private Filter | pushFilter
Holds the push filter for trigger conditions requiring an early push. |
| private Level | pushLevel
Holds the push level for this handler. |
| private volatile boolean | sealed
Used to turn off security checks. |
| private Session | session
Holds the session object used to generate emails. |
| private int | size
The number of log records in the buffer. |
| private Formatter | subjectFormatter
Holds the formatter used to create the subject line of the email. |
| Access | Constructor and Description |
|---|---|
| public | |
| public | MailHandler(final int
of the internal buffer. capacity)Creates a MailHandler that is configured by the LogManager configuration properties but overrides the LogManager capacity with the given capacity. |
| public | MailHandler(final Properties
a non null properties object. props)Creates a mail handler with the given mail properties. |
| Modifier and Type | Method and Description |
|---|---|
| private boolean | Returns: true if the size was changed.Expand or shrink the attachment filters with the attachment formatters. |
| private boolean | Returns: true if size was changed.Expand or shrink the attachment name formatters with the attachment formatters. |
| private boolean | Returns: true if restricted headers are allowed.Determines if restricted headers are allowed in the current environment. |
| private void | appendContentLang(final MimePart
the mime part. p, final Locale the locale to append. l)Appends the content language to the given mime part. |
| private void | appendFileName(final Part
to append to. part, final String non null string to append. chunk)Constructs a file name from a formatter. |
| private void | appendFileName0(final Part
to append to. part, String non null string to append. chunk)It is assumed that file names are short and that in most cases getTail will be the only method that will produce a result. |
| private void | appendSubject(final Message
to append to. msg, final String non null string to append. chunk)Constructs a subject line from a formatter. |
| private void | appendSubject0(final Message
to append to. msg, String non null string to append. chunk)It is assumed that subject lines are short and that in most cases getTail will be the only method that will produce a result. |
| private static String | Returns: the error message.the index. i)Outline the creation of the index error message. |
| private static MessagingException | Returns: either the required or the optional exception.the exception expected to see as a reported failure. required, Exception the suppressed exception. optional)Try to attach a suppressed exception to a MessagingException in any order that is possible. |
| private static RuntimeException | Returns: a RuntimeException to represent the type of error.the exception message. msg)A factory used to create a common attachment mismatch type. |
| private static RuntimeException | Returns: a RuntimeException populated with a message.the expected array length. expected, int the array length that was given. found)Outline the attachment mismatch message. |
| private void | |
| private void | clearMatches(int
the lowest filter index to clear. index)Clear previous matches when the filters are modified and there are existing log records that were matched. |
| public void | close()
Implements abstract java. |
| pack-priv final String | Returns: return the mime type or null for text/plain.any char sequence or null. chunk)Determines the mimeType of a formatter from the getHead call. |
| pack-priv final String | Returns: return the mime type or null, meaning text/plain.the formatter or null. f)Determines the mimeType of a formatter by the class name. |
| private String | Returns: the type with a specified encoding.the content type. type, String the java charset name. encoding)Replaces the charset parameter with the current encoding. |
| private MimeBodyPart | Returns: a body part with default headers set.Factory to create the in-line body part. |
| private MimeBodyPart | Returns: a body part with default headers set.the attachment index. index)Factory to create the attachment body part. |
| private static Formatter | Returns: a new SimpleFormatter.Factory method used to create a java.util.logging.SimpleFormatter. |
| private ErrorManager | Returns: the super error manager or a new ErrorManager.Used to get or create the default ErrorManager used before init. |
| private String | Returns: the description.the comparator. c, Level the pushLevel. l, Filter the pushFilter f)Gets the description for the MimeMessage itself. |
| private String | Returns: the description for the body part.the content formatter. f, Filter the content filter. filter, Formatter the naming formatter. name)Creates a description for a body part. |
| private static Filter[] | |
| private static Formatter[] | |
| private void | envelopeFor(Message
the Message to write the envelope information. msg, boolean true for high priority. priority)Creates all of the envelope information for a message. |
| public void | flush()
Implements abstract java. |
| private String | |
| private Object | Returns: null for the boot class loader, a class loader, or a marker object to signal that no modification was required.null for boot class loader, a class loader, a class used to
get the class loader, or a source object to get the class loader. ccl)Replaces the current context class loader with our class loader. |
| public final Filter[] | |
| public final Formatter[] | |
| public final Formatter[] | Returns: non null array of attachment name formatters.Gets the attachment name formatters. |
| public final synchronized Authenticator | Returns: an Authenticator or null if none is required.Gets the Authenticator used to login to the email server. |
| public final synchronized int | |
| private String | Returns: a class name that represents the given formatter.the formatter. f)Gets a class name represents the behavior of the formatter. |
| public final synchronized Comparator | Returns: the LogRecord comparator.Gets the comparator used to order all LogRecord objects prior to formatting. |
| private String | Returns: the mime type or null for text/plain.the file name or class name. name)Determines the mimeType from the given file name. |
| public synchronized String | Returns: The encoding name. May be null, which indicates the default encoding should be used.Overrides java. |
| private String | Returns: the java charset name, never null.Gets the encoding set for this handler, mime encoding, or file encoding. |
| public ErrorManager | Returns: the ErrorManager for this HandlerOverrides java. |
| public Filter | Returns: a Filter object (may be null)Overrides java. |
| public synchronized Formatter | Returns: the Formatter (may be null).Overrides java. |
| public Level | Returns: the level of messages being logged.Overrides java. |
| private String | Returns: the local host or null.the service to check. s)Gets the local host from the given service object. |
| public final Properties | Returns: a non null properties object.Gets a copy of the mail properties used for the session. |
| private int | Returns: the filter index or MUTEX_PUBLISH if unknown.This is used to get the filter index from when |
| public final synchronized Filter | |
| public final synchronized Level | |
| private Session | Returns: the session from the given message.the message. msg)Google App Engine doesn't support Message.getSession. |
| public final synchronized Formatter | |
| private void | |
| private static boolean | |
| private String | |
| private synchronized void | init(final Properties
the given mail properties. Maybe null and are never
captured by this handler. props)Configures the handler properties from the log manager. |
| private void | initAttachmentFilters(final String
the handler class name used as the prefix. p)Parses LogManager string values into objects used by this handler. |
| private void | initAttachmentFormaters(final String
the handler class name used as the prefix. p)Parses LogManager string values into objects used by this handler. |
| private void | initAttachmentNames(final String
the handler class name used as the prefix. p)Parses LogManager string values into objects used by this handler. |
| private void | initAuthenticator(final String
the handler class name used as the prefix. p)Parses LogManager string values into objects used by this handler. |
| private void | initCapacity(final String
the handler class name used as the prefix. p)Parses LogManager string values into objects used by this handler. |
| private void | initComparator(final String
the handler class name used as the prefix. p)Parses LogManager string values into objects used by this handler. |
| private void | initEncoding(final String
the handler class name used as the prefix. p)Parses LogManager string values into objects used by this handler. |
| private void | initErrorManager(final String
the handler class name used as the prefix. p)Parses LogManager string values into objects used by this handler. |
| private void | initFilter(final String
the handler class name used as the prefix. p)Parses LogManager string values into objects used by this handler. |
| private void | initFormatter(final String
the handler class name used as the prefix. p)Parses LogManager string values into objects used by this handler. |
| private void | |
| private void | initPushFilter(final String
the handler class name used as the prefix. p)Parses LogManager string values into objects used by this handler. |
| private void | initPushLevel(final String
the handler class name used as the prefix. p)Parses LogManager string values into objects used by this handler. |
| private Session | Returns: the session that was created and assigned.Creates a session using a proxy properties object. |
| private void | initSubject(final String
the handler class name used as the prefix. p)Parses LogManager string values into objects used by this handler. |
| private void | |
| private Object | |
| private boolean | Returns: true if the LogRecord would be formatted.a LogRecord record)Check if any attachment would actually format the given LogRecord. |
| private static boolean | Returns: true if the given string is null or zero length.the char sequence. s)Checks a char sequence value for null or empty. |
| public boolean | Returns: true if the LogRecord would be logged.a LogRecord record)Overrides java. |
| pack-priv final boolean | Returns: true if the throwable is a missing content exception.the message without content. msg, Throwable the throwable chain to test. t)Determines if the given throwable is a no content exception. |
| private boolean | Returns: true if the LogRecord triggers an email push.a LogRecord record)Check if this Handler would push after storing the LogRecord into its internal buffer. |
| private Locale | |
| public void | |
| public void | |
| public void | publish(final LogRecord
description of the log event. record)Implements abstract java. |
| private void | |
| public void | |
| private void | push(final boolean
true for high priority otherwise false for normal. priority, final int the error manager code. code)Used to perform push or flush. |
| private Filter[] | Returns: a read only array of filters.Gets the attachment filters using a happens-before relationship between this method and setAttachmentFilters. |
| private void | |
| protected void | reportError(String
a descriptive string (may be null) msg, Exception an exception (may be null) ex, int an error code defined in ErrorManager code)Overrides java. |
| private void | reportError(Message
the mime message. msg, Exception the original exception. ex, int the ErrorManager code. code)Converts a mime message to a raw string or formats the reason why message can't be changed to raw string and reports it. |
| private void | reportFilterError(final LogRecord
that was not formatted. record)Used when a log record was loggable prior to being inserted into the buffer but at the time of formatting was no longer loggable. |
| private void | reportLinkageError(final Throwable
the linkage error or a RuntimeException. le, final int the ErrorManager code. code)Reports the given linkage error or runtime exception. |
| private void | reportNonDiscriminating(final Object
the test object must be non null. o, final Object the possible intern, must be non null. found)Reports equals implementations that do not discriminate between objects of different types or subclass types. |
| private void | reportNonSymmetric(final Object
the test object must be non null. o, final Object the possible intern, must be non null. found)Reports symmetric contract violations an equals implementation. |
| private void | reportNullError(final int
the ErrorManager code. code)Used to outline the bytes to report a null pointer exception. |
| private void | reportUnexpectedSend(MimeMessage
the MimeMessage. msg, String the verify enum. verify, Exception the exception that caused the problem or null. cause)Reports that an empty content message was sent and should not have been. |
| private void | reportUnPublishedError(LogRecord
the record or null. record)Report to the error manager that a logging loop was detected and we are going to break the cycle of messages. |
| private void | |
| private void | saveChangesNoContent(final Message
the message requiring save changes. abort, final String the error description. msg)Handles all exceptions thrown when save changes is called on a message that doesn't have any content. |
| private void | |
| private void | setAcceptLang(final Part
the part to set. p)Sets the accept language to the default locale of the JVM. |
| public final void | setAttachmentFilters(Filter...
a non null array of filters. A null
index value is allowed. A null value means that all
records are allowed for the attachment at that index. filters)Sets the attachment filters. |
| public final void | setAttachmentFormatters(Formatter...
a non null array of formatters. formatters)Sets the attachment Formatter object for this handler. |
| public final void | setAttachmentNames(final String...
an array of names. names)Sets the attachment file name for each attachment. |
| public final void | setAttachmentNames(Formatter...
and array of attachment name formatters. formatters)Sets the attachment file name formatters. |
| public final void | setAuthenticator(final Authenticator
an Authenticator object or null if none is required. auth)Sets the Authenticator used to login to the email server. |
| public final void | setAuthenticator(final char...
a password, empty array can be used to only supply a
user name set by mail.user property, or null if no credentials
are required. password)Sets the Authenticator used to login to the email server. |
| private void | setAuthenticator0(final Authenticator
see public method. auth)A private hook to handle possible future overrides. |
| private void | setAutoSubmitted(final Message
the message. msg)Signals that this message was generated by automatic process. |
| private synchronized void | |
| public final synchronized void | setComparator(Comparator<? super LogRecord>
the LogRecord comparator. c)Sets the comparator used to order all LogRecord objects prior to formatting. |
| private void | setContent(MimePart
the part to assign. part, CharSequence the formatted data. buf, String the mime type or null, meaning text/plain. type)Set the content for a part using the encoding assigned to the handler. |
| private void | |
| private void | setDefaultRecipient(final Message
the message msg, final Message.the recipient type. typeComputes the default to-address if none was specified. |
| public void | setEncoding(String
The name of a supported character encoding. May be
null, to indicate the default platform encoding. encoding)Overrides java. |
| private void | setEncoding0(String
any encoding name or null for the default. e)
Set the character encoding used by this handler.
|
| private void | setErrorContent(MimeMessage
the message with or without content. msg, String the verify enum. verify, Throwable the throwable or null. t)Creates and sets the message content from the given Throwable. |
| public void | setErrorManager(final ErrorManager
the new ErrorManager em)Overrides java. |
| private void | setErrorManager0(final ErrorManager
a non null error manager. em)
Sets the error manager on this handler and the super handler.
|
| public void | setFilter(final Filter
a Filter object (may be null) newFilter)Overrides java. |
| public synchronized void | setFormatter(Formatter
the Formatter to use (may not be null) newFormatter)Overrides java. |
| private void | |
| private void | setIncompleteCopy(final Message
the message. msg)Used to signal that body parts are missing from a message. |
| public void | setLevel(final Level
the new value for the log level newLevel)Overrides java. |
| private void | |
| public final void | setMailProperties(Properties
a non null properties object. props)Sets the mail properties used for the session. |
| private void | setMailProperties0(Properties
see public method. props)A private hook to handle overrides when the public method is declared non final. |
| private void | setMatchedPart(int
the filter index. index)This is used to record the filter index when |
| private void | |
| public final synchronized void | |
| public final synchronized void | |
| private boolean | Returns: true if the key was contained in the session.the message. msg, final String the key to search in the session. key, final Message.the recipient type. typeSets the recipient for the given message. |
| private void | |
| private void | |
| public final void | |
| public final void | |
| private void | |
| private String | |
| private String | Returns: the throwable with a stack trace or the literal null.any throwable or null. t)Converts a throwable to a message string. |
| private AddressException | Returns: the too many addresses exception.the addresses, never null. address, int the starting address to display. offset)A common factory used to create the too many addresses exception. |
| private String | Returns: the raw string or null if msg was null.a Message object. msg)Converts an email message to a raw string. |
| private String | |
| private boolean | Returns: true if the mutex was acquired.Used to detect reentrance by the current thread to the publish method. |
| private Session | Returns: the current session or null if no verify is required.Used to update the cached session object based on changes in mail properties or authenticator. |
| private static void | verifyAddresses(Address[]
any address array, null or empty. all)Calls validate for every address given. |
| private static InetAddress | Returns: the address.the host or null. host)Perform a lookup of the host address or FQDN. |
| private static void | verifyProperties(Session
the session. session, String the mail protocol. protocol)Cache common session properties into the LogManagerProperties. |
| private void | verifySettings(final Session
the current session or null. session)Checks all of the settings if the caller requests a verify and a verify was not performed yet and no verify is in progress. |
| private void | verifySettings0(Session
the current session. session, String the type of verify to perform. verify)Checks all of the settings using the given setting. |
| private Message | Returns: null if there are no records or is currently in a push. Otherwise a new message is created with a formatted message and attached session.the error manager code. code)Formats all records in the buffer and places the output in a Message. |
| private Message | Returns: null if there are no records or is currently in a push. Otherwise a new message is created with a formatted message and attached session.Formats all records in the buffer and places the output in a Message. |