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