public class MailHandler extends Handler
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", "me@example.com"); 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 = me@example.com com.sun.mail.util.logging.MailHandler.level = WARNING com.sun.mail.util.logging.MailHandler.verify = localFor 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 = me@example.com com.foo.MyHandler.level = WARNING com.foo.MyHandler.verify = localAll 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. 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 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. } }
Constructor and Description |
---|
MailHandler()
Creates a MailHandler that is configured by the
LogManager configuration properties.
|
MailHandler(int capacity)
Creates a MailHandler that is configured by the
LogManager configuration properties but overrides the
LogManager capacity with the given capacity.
|
MailHandler(Properties props)
Creates a mail handler with the given mail properties.
|
Modifier and Type | Method and Description |
---|---|
void |
close()
Prevents any other records from being published.
|
void |
flush()
Pushes any buffered records to the email server as normal priority.
|
Filter[] |
getAttachmentFilters()
Gets the attachment filters.
|
Formatter[] |
getAttachmentFormatters()
Gets the attachment formatters.
|
Formatter[] |
getAttachmentNames()
Gets the attachment name formatters.
|
Authenticator |
getAuthenticator()
Gets the Authenticator used to login to the email server.
|
int |
getCapacity()
Gets the number of log records the internal buffer can hold.
|
Comparator<? super LogRecord> |
getComparator()
Gets the comparator used to order all LogRecord objects prior
to formatting.
|
String |
getEncoding()
Return the character encoding for this Handler.
|
ErrorManager |
getErrorManager()
Retrieves the ErrorManager for this Handler.
|
Filter |
getFilter()
Get the current Filter for this Handler.
|
Formatter |
getFormatter()
Return the Formatter for this Handler.
|
Level |
getLevel()
Get the log level specifying which messages will be logged by this
Handler.
|
Properties |
getMailProperties()
Gets a copy of the mail properties used for the session.
|
Filter |
getPushFilter()
Gets the push filter.
|
Level |
getPushLevel()
Gets the push level.
|
Formatter |
getSubject()
Gets the formatter used to create the subject line.
|
boolean |
isLoggable(LogRecord record)
Check if this Handler would actually log a given
LogRecord into its internal buffer.
|
void |
postConstruct()
A callback method for when this object is about to be placed into
commission.
|
void |
preDestroy()
A callback method for when this object is about to be decommissioned.
|
void |
publish(LogRecord record)
Stores a LogRecord in the internal buffer.
|
void |
push()
Pushes any buffered records to the email server as high importance with
urgent priority.
|
protected void |
reportError(String msg,
Exception ex,
int code)
Protected convenience method to report an error to this Handler's
ErrorManager.
|
void |
setAttachmentFilters(Filter... filters)
Sets the attachment filters.
|
void |
setAttachmentFormatters(Formatter... formatters)
Sets the attachment Formatter object for this handler.
|
void |
setAttachmentNames(Formatter... formatters)
Sets the attachment file name formatters.
|
void |
setAttachmentNames(String... names)
Sets the attachment file name for each attachment.
|
void |
setAuthenticator(Authenticator auth)
Sets the Authenticator used to login to the email server.
|
void |
setAuthenticator(char... password)
Sets the Authenticator used to login to the email server.
|
void |
setComparator(Comparator<? super LogRecord> c)
Sets the comparator used to order all LogRecord objects prior
to formatting.
|
void |
setEncoding(String encoding)
Set the character encoding used by this Handler.
|
void |
setErrorManager(ErrorManager em)
Define an ErrorManager for this Handler.
|
void |
setFilter(Filter newFilter)
Set a Filter to control output on this Handler.
|
void |
setFormatter(Formatter newFormatter)
Set a Formatter.
|
void |
setLevel(Level newLevel)
Set the log level specifying which message levels will be
logged by this Handler.
|
void |
setMailProperties(Properties props)
Sets the mail properties used for the session.
|
void |
setPushFilter(Filter filter)
Sets the push filter.
|
void |
setPushLevel(Level level)
Sets the push level.
|
void |
setSubject(Formatter format)
Sets the subject formatter for email.
|
void |
setSubject(String subject)
Sets a literal string for the email subject.
|
public MailHandler()
SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").public MailHandler(int capacity)
capacity
- of the internal buffer.IllegalArgumentException
- if capacity less than one.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").public MailHandler(Properties props)
props
- a non null properties object.NullPointerException
- if props is null.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").public boolean isLoggable(LogRecord record)
This method checks if the LogRecord has an appropriate level and whether it satisfies any Filter including any attachment filters. However it does not check whether the LogRecord would result in a "push" of the buffer contents.
isLoggable
in class Handler
record
- a LogRecordpublic void publish(LogRecord record)
The isLoggable method is called to check if the given log record is loggable. If the given record is loggable, it is copied into an internal buffer. Then the record's level property is compared with the push level. If the given level of the LogRecord is greater than or equal to the push level then the push filter is called. If no push filter exists, the push filter returns true, or the capacity of the internal buffer has been reached then all buffered records are formatted into one email and sent to the server.
public void postConstruct()
org.glassfish.hk2.api.PostConstruct
interface. If this class is
loaded via a lifecycle managed environment other than HK2 then it is
recommended that this method is called either directly or through
extending this class to signal that this object is ready for use.public void preDestroy()
org.glassfish.hk2.api.PreDestory
interface. If this class is loaded via a lifecycle managed environment
other than HK2 then it is recommended that this method is called either
directly or through extending this class to signal that this object will
be destroyed.public void push()
flush()
public void flush()
public void close()
If this Handler is only implicitly closed by the LogManager, then verification should be turned on.
close
in class Handler
SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").flush()
public void setLevel(Level newLevel)
setLevel
in class Handler
newLevel
- the new value for the log levelNullPointerException
- if newLevel is null.SecurityException
- if a security manager exists and
the caller does not have LoggingPermission("control").public Level getLevel()
public ErrorManager getErrorManager()
getErrorManager
in class Handler
SecurityException
- if a security manager exists and if the caller
does not have LoggingPermission("control").public void setErrorManager(ErrorManager em)
The ErrorManager's "error" method will be invoked if any errors occur while using this Handler.
setErrorManager
in class Handler
em
- the new ErrorManagerSecurityException
- if a security manager exists and if the
caller does not have LoggingPermission("control").NullPointerException
- if the given error manager is null.public Filter getFilter()
public void setFilter(Filter newFilter)
For each call of publish the Handler will call this Filter (if it is non-null) to check if the LogRecord should be published or discarded.
setFilter
in class Handler
newFilter
- a Filter object (may be null)SecurityException
- if a security manager exists and if the caller
does not have LoggingPermission("control").public String getEncoding()
getEncoding
in class Handler
public void setEncoding(String encoding) throws UnsupportedEncodingException
The encoding should be set before any LogRecords are written to the Handler.
setEncoding
in class Handler
encoding
- The name of a supported character encoding. May be
null, to indicate the default platform encoding.SecurityException
- if a security manager exists and if the caller
does not have LoggingPermission("control").UnsupportedEncodingException
- if the named encoding is not
supported.public Formatter getFormatter()
getFormatter
in class Handler
public void setFormatter(Formatter newFormatter) throws SecurityException
Some Handlers may not use Formatters, in which case the Formatter will be remembered, but not used.
setFormatter
in class Handler
newFormatter
- the Formatter to use (may not be null)SecurityException
- if a security manager exists and if the caller
does not have LoggingPermission("control").NullPointerException
- if the given formatter is null.public final Level getPushLevel()
public final void setPushLevel(Level level)
level
- Level object.NullPointerException
- if level is null.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").IllegalStateException
- if called from inside a push.public final Filter getPushFilter()
public final void setPushFilter(Filter filter)
filter
- push filter or nullSecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").IllegalStateException
- if called from inside a push.public final Comparator<? super LogRecord> getComparator()
public final void setComparator(Comparator<? super LogRecord> c)
c
- the LogRecord comparator.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").IllegalStateException
- if called from inside a push.public final int getCapacity()
public final Authenticator getAuthenticator()
SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").public final void setAuthenticator(Authenticator auth)
auth
- an Authenticator object or null if none is required.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").IllegalStateException
- if called from inside a push.public final void setAuthenticator(char... password)
password
- a password or null if none is required.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").IllegalStateException
- if called from inside a push.String.toCharArray()
public final void setMailProperties(Properties props)
props
- a non null properties object.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").NullPointerException
- if props is null.IllegalStateException
- if called from inside a push.public final Properties getMailProperties()
SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").public final Filter[] getAttachmentFilters()
public final void setAttachmentFilters(Filter... filters)
filters
- 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.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").NullPointerException
- if filters is nullIndexOutOfBoundsException
- if the number of attachment
name formatters do not match the number of attachment formatters.IllegalStateException
- if called from inside a push.public final Formatter[] getAttachmentFormatters()
public final void setAttachmentFormatters(Formatter... formatters)
formatters
- a non null array of formatters.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").NullPointerException
- if the given array or any array index is
null.IllegalStateException
- if called from inside a push.public final Formatter[] getAttachmentNames()
public final void setAttachmentNames(String... names)
names
- an array of names.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").IndexOutOfBoundsException
- if the number of attachment
names do not match the number of attachment formatters.IllegalArgumentException
- if any name is empty.NullPointerException
- if any given array or name is null.IllegalStateException
- if called from inside a push.Character.isISOControl(char)
,
Character.isISOControl(int)
public final void setAttachmentNames(Formatter... formatters)
formatters
- and array of attachment name formatters.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").IndexOutOfBoundsException
- if the number of attachment
name formatters do not match the number of attachment formatters.NullPointerException
- if any given array or name is null.IllegalStateException
- if called from inside a push.Character.isISOControl(char)
,
Character.isISOControl(int)
public final Formatter getSubject()
public final void setSubject(String subject)
subject
- a non null string.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").NullPointerException
- if subject is null.IllegalStateException
- if called from inside a push.Character.isISOControl(char)
,
Character.isISOControl(int)
public final void setSubject(Formatter format)
format
- the subject formatter.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").NullPointerException
- if format is null.IllegalStateException
- if called from inside a push.Character.isISOControl(char)
,
Character.isISOControl(int)
protected void reportError(String msg, Exception ex, int code)
reportError
in class Handler
msg
- a descriptive string (may be null)ex
- an exception (may be null)code
- an error code defined in ErrorManagerCopyright © 2017 JBoss by Red Hat. All rights reserved.