1 /*
   2  * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.util.logging;
  27 
  28 /**
  29  * <tt>Handler</tt> that buffers requests in a circular buffer in memory.
  30  * <p>
  31  * Normally this <tt>Handler</tt> simply stores incoming <tt>LogRecords</tt>
  32  * into its memory buffer and discards earlier records.  This buffering
  33  * is very cheap and avoids formatting costs.  On certain trigger
  34  * conditions, the <tt>MemoryHandler</tt> will push out its current buffer
  35  * contents to a target <tt>Handler</tt>, which will typically publish
  36  * them to the outside world.
  37  * <p>
  38  * There are three main models for triggering a push of the buffer:
  39  * <ul>
  40  * <li>
  41  * An incoming <tt>LogRecord</tt> has a type that is greater than
  42  * a pre-defined level, the <tt>pushLevel</tt>. </li>
  43  * <li>
  44  * An external class calls the <tt>push</tt> method explicitly. </li>
  45  * <li>
  46  * A subclass overrides the <tt>log</tt> method and scans each incoming
  47  * <tt>LogRecord</tt> and calls <tt>push</tt> if a record matches some
  48  * desired criteria. </li>
  49  * </ul>
  50  * <p>
  51  * <b>Configuration:</b>
  52  * By default each <tt>MemoryHandler</tt> is initialized using the following
  53  * <tt>LogManager</tt> configuration properties where <tt>&lt;handler-name&gt;</tt>
  54  * refers to the fully-qualified class name of the handler.
  55  * If properties are not defined
  56  * (or have invalid values) then the specified default values are used.
  57  * If no default value is defined then a RuntimeException is thrown.
  58  * <ul>
  59  * <li>   &lt;handler-name&gt;.level
  60  *        specifies the level for the <tt>Handler</tt>
  61  *        (defaults to <tt>Level.ALL</tt>). </li>
  62  * <li>   &lt;handler-name&gt;.filter
  63  *        specifies the name of a <tt>Filter</tt> class to use
  64  *        (defaults to no <tt>Filter</tt>). </li>
  65  * <li>   &lt;handler-name&gt;.size
  66  *        defines the buffer size (defaults to 1000). </li>
  67  * <li>   &lt;handler-name&gt;.push
  68  *        defines the <tt>pushLevel</tt> (defaults to <tt>level.SEVERE</tt>). </li>
  69  * <li>   &lt;handler-name&gt;.target
  70  *        specifies the name of the target <tt>Handler </tt> class.
  71  *        (no default). </li>
  72  * </ul>
  73  * <p>
  74  * For example, the properties for {@code MemoryHandler} would be:
  75  * <ul>
  76  * <li>   java.util.logging.MemoryHandler.level=INFO </li>
  77  * <li>   java.util.logging.MemoryHandler.formatter=java.util.logging.SimpleFormatter </li>
  78  * </ul>
  79  * <p>
  80  * For a custom handler, e.g. com.foo.MyHandler, the properties would be:
  81  * <ul>
  82  * <li>   com.foo.MyHandler.level=INFO </li>
  83  * <li>   com.foo.MyHandler.formatter=java.util.logging.SimpleFormatter </li>
  84  * </ul>
  85  * <p>
  86  * @since 1.4
  87  */
  88 
  89 public class MemoryHandler extends Handler {
  90     private final static int DEFAULT_SIZE = 1000;
  91     private volatile Level pushLevel;
  92     private int size;
  93     private Handler target;
  94     private LogRecord buffer[];
  95     int start, count;
  96 
  97     // Private method to configure a MemoryHandler from LogManager
  98     // properties and/or default values as specified in the class
  99     // javadoc.
 100     private void configure() {
 101         LogManager manager = LogManager.getLogManager();
 102         String cname = getClass().getName();
 103 
 104         pushLevel = manager.getLevelProperty(cname +".push", Level.SEVERE);
 105         size = manager.getIntProperty(cname + ".size", DEFAULT_SIZE);
 106         if (size <= 0) {
 107             size = DEFAULT_SIZE;
 108         }
 109         setLevel(manager.getLevelProperty(cname +".level", Level.ALL));
 110         setFilter(manager.getFilterProperty(cname +".filter", null));
 111         setFormatter(manager.getFormatterProperty(cname +".formatter", new SimpleFormatter()));
 112     }
 113 
 114     /**
 115      * Create a <tt>MemoryHandler</tt> and configure it based on
 116      * <tt>LogManager</tt> configuration properties.
 117      */
 118     public MemoryHandler() {
 119         doWithControlPermission(this::configure);
 120 
 121         LogManager manager = LogManager.getLogManager();
 122         String handlerName = getClass().getName();
 123         String targetName = manager.getProperty(handlerName+".target");
 124         if (targetName == null) {
 125             throw new RuntimeException("The handler " + handlerName
 126                     + " does not specify a target");
 127         }
 128         Class<?> clz;
 129         try {
 130             clz = ClassLoader.getSystemClassLoader().loadClass(targetName);
 131             target = (Handler) clz.newInstance();
 132         } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
 133             throw new RuntimeException("MemoryHandler can't load handler target \"" + targetName + "\"" , e);
 134         }
 135         init();
 136     }
 137 
 138     // Initialize.  Size is a count of LogRecords.
 139     private void init() {
 140         buffer = new LogRecord[size];
 141         start = 0;
 142         count = 0;
 143     }
 144 
 145     /**
 146      * Create a <tt>MemoryHandler</tt>.
 147      * <p>
 148      * The <tt>MemoryHandler</tt> is configured based on <tt>LogManager</tt>
 149      * properties (or their default values) except that the given <tt>pushLevel</tt>
 150      * argument and buffer size argument are used.
 151      *
 152      * @param target  the Handler to which to publish output.
 153      * @param size    the number of log records to buffer (must be greater than zero)
 154      * @param pushLevel  message level to push on
 155      *
 156      * @throws IllegalArgumentException if {@code size is <= 0}
 157      */
 158     public MemoryHandler(Handler target, int size, Level pushLevel) {
 159         if (target == null || pushLevel == null) {
 160             throw new NullPointerException();
 161         }
 162         if (size <= 0) {
 163             throw new IllegalArgumentException();
 164         }
 165         doWithControlPermission(this::configure);
 166         this.target = target;
 167         this.pushLevel = pushLevel;
 168         this.size = size;
 169         init();
 170     }
 171 
 172     /**
 173      * Store a <tt>LogRecord</tt> in an internal buffer.
 174      * <p>
 175      * If there is a <tt>Filter</tt>, its <tt>isLoggable</tt>
 176      * method is called to check if the given log record is loggable.
 177      * If not we return.  Otherwise the given record is copied into
 178      * an internal circular buffer.  Then the record's level property is
 179      * compared with the <tt>pushLevel</tt>. If the given level is
 180      * greater than or equal to the <tt>pushLevel</tt> then <tt>push</tt>
 181      * is called to write all buffered records to the target output
 182      * <tt>Handler</tt>.
 183      *
 184      * @param  record  description of the log event. A null record is
 185      *                 silently ignored and is not published
 186      */
 187     @Override
 188     public synchronized void publish(LogRecord record) {
 189         if (!isLoggable(record)) {
 190             return;
 191         }
 192         int ix = (start+count)%buffer.length;
 193         buffer[ix] = record;
 194         if (count < buffer.length) {
 195             count++;
 196         } else {
 197             start++;
 198             start %= buffer.length;
 199         }
 200         if (record.getLevel().intValue() >= pushLevel.intValue()) {
 201             push();
 202         }
 203     }
 204 
 205     /**
 206      * Push any buffered output to the target <tt>Handler</tt>.
 207      * <p>
 208      * The buffer is then cleared.
 209      */
 210     public synchronized void push() {
 211         for (int i = 0; i < count; i++) {
 212             int ix = (start+i)%buffer.length;
 213             LogRecord record = buffer[ix];
 214             target.publish(record);
 215         }
 216         // Empty the buffer.
 217         start = 0;
 218         count = 0;
 219     }
 220 
 221     /**
 222      * Causes a flush on the target <tt>Handler</tt>.
 223      * <p>
 224      * Note that the current contents of the <tt>MemoryHandler</tt>
 225      * buffer are <b>not</b> written out.  That requires a "push".
 226      */
 227     @Override
 228     public void flush() {
 229         target.flush();
 230     }
 231 
 232     /**
 233      * Close the <tt>Handler</tt> and free all associated resources.
 234      * This will also close the target <tt>Handler</tt>.
 235      *
 236      * @exception  SecurityException  if a security manager exists and if
 237      *             the caller does not have <tt>LoggingPermission("control")</tt>.
 238      */
 239     @Override
 240     public void close() throws SecurityException {
 241         target.close();
 242         setLevel(Level.OFF);
 243     }
 244 
 245     /**
 246      * Set the <tt>pushLevel</tt>.  After a <tt>LogRecord</tt> is copied
 247      * into our internal buffer, if its level is greater than or equal to
 248      * the <tt>pushLevel</tt>, then <tt>push</tt> will be called.
 249      *
 250      * @param newLevel the new value of the <tt>pushLevel</tt>
 251      * @exception  SecurityException  if a security manager exists and if
 252      *             the caller does not have <tt>LoggingPermission("control")</tt>.
 253      */
 254     public synchronized void setPushLevel(Level newLevel) throws SecurityException {
 255         if (newLevel == null) {
 256             throw new NullPointerException();
 257         }
 258         checkPermission();
 259         pushLevel = newLevel;
 260     }
 261 
 262     /**
 263      * Get the <tt>pushLevel</tt>.
 264      *
 265      * @return the value of the <tt>pushLevel</tt>
 266      */
 267     public Level getPushLevel() {
 268         return pushLevel;
 269     }
 270 
 271     /**
 272      * Check if this <tt>Handler</tt> would actually log a given
 273      * <tt>LogRecord</tt> into its internal buffer.
 274      * <p>
 275      * This method checks if the <tt>LogRecord</tt> has an appropriate level and
 276      * whether it satisfies any <tt>Filter</tt>.  However it does <b>not</b>
 277      * check whether the <tt>LogRecord</tt> would result in a "push" of the
 278      * buffer contents. It will return false if the <tt>LogRecord</tt> is null.
 279      * <p>
 280      * @param record  a <tt>LogRecord</tt>
 281      * @return true if the <tt>LogRecord</tt> would be logged.
 282      *
 283      */
 284     @Override
 285     public boolean isLoggable(LogRecord record) {
 286         return super.isLoggable(record);
 287     }
 288 }