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