1/*
2 * Copyright (c) 2000, 2013, 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
26package java.util.logging;
27
28/**
29 * {@code Handler} that buffers requests in a circular buffer in memory.
30 * <p>
31 * Normally this {@code Handler} simply stores incoming {@code LogRecords}
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 {@code MemoryHandler} will push out its current buffer
35 * contents to a target {@code Handler}, 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 {@code LogRecord} has a type that is greater than
42 * a pre-defined level, the {@code pushLevel}. </li>
43 * <li>
44 * An external class calls the {@code push} method explicitly. </li>
45 * <li>
46 * A subclass overrides the {@code log} method and scans each incoming
47 * {@code LogRecord} and calls {@code push} if a record matches some
48 * desired criteria. </li>
49 * </ul>
50 * <p>
51 * <b>Configuration:</b>
52 * By default each {@code MemoryHandler} is initialized using the following
53 * {@code LogManager} configuration properties where {@code <handler-name>}
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 {@code Handler}
61 *        (defaults to {@code Level.ALL}). </li>
62 * <li>   &lt;handler-name&gt;.filter
63 *        specifies the name of a {@code Filter} class to use
64 *        (defaults to no {@code Filter}). </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 {@code pushLevel} (defaults to {@code level.SEVERE}). </li>
69 * <li>   &lt;handler-name&gt;.target
70 *        specifies the name of the target {@code Handler } 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 *
86 * @since 1.4
87 */
88
89public 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    /**
98     * Create a {@code MemoryHandler} and configure it based on
99     * {@code LogManager} configuration properties.
100     */
101    public MemoryHandler() {
102        // configure with specific defaults for MemoryHandler
103        super(Level.ALL, new SimpleFormatter(), null);
104
105        LogManager manager = LogManager.getLogManager();
106        String cname = getClass().getName();
107        pushLevel = manager.getLevelProperty(cname +".push", Level.SEVERE);
108        size = manager.getIntProperty(cname + ".size", DEFAULT_SIZE);
109        if (size <= 0) {
110            size = DEFAULT_SIZE;
111        }
112        String targetName = manager.getProperty(cname+".target");
113        if (targetName == null) {
114            throw new RuntimeException("The handler " + cname
115                    + " does not specify a target");
116        }
117        Class<?> clz;
118        try {
119            clz = ClassLoader.getSystemClassLoader().loadClass(targetName);
120            @SuppressWarnings("deprecation")
121            Object o = clz.newInstance();
122            target = (Handler) o;
123        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
124            throw new RuntimeException("MemoryHandler can't load handler target \"" + targetName + "\"" , e);
125        }
126        init();
127    }
128
129    // Initialize.  Size is a count of LogRecords.
130    private void init() {
131        buffer = new LogRecord[size];
132        start = 0;
133        count = 0;
134    }
135
136    /**
137     * Create a {@code MemoryHandler}.
138     * <p>
139     * The {@code MemoryHandler} is configured based on {@code LogManager}
140     * properties (or their default values) except that the given {@code pushLevel}
141     * argument and buffer size argument are used.
142     *
143     * @param target  the Handler to which to publish output.
144     * @param size    the number of log records to buffer (must be greater than zero)
145     * @param pushLevel  message level to push on
146     *
147     * @throws IllegalArgumentException if {@code size is <= 0}
148     */
149    public MemoryHandler(Handler target, int size, Level pushLevel) {
150        // configure with specific defaults for MemoryHandler
151        super(Level.ALL, new SimpleFormatter(), null);
152
153        if (target == null || pushLevel == null) {
154            throw new NullPointerException();
155        }
156        if (size <= 0) {
157            throw new IllegalArgumentException();
158        }
159        this.target = target;
160        this.pushLevel = pushLevel;
161        this.size = size;
162        init();
163    }
164
165    /**
166     * Store a {@code LogRecord} in an internal buffer.
167     * <p>
168     * If there is a {@code Filter}, its {@code isLoggable}
169     * method is called to check if the given log record is loggable.
170     * If not we return.  Otherwise the given record is copied into
171     * an internal circular buffer.  Then the record's level property is
172     * compared with the {@code pushLevel}. If the given level is
173     * greater than or equal to the {@code pushLevel} then {@code push}
174     * is called to write all buffered records to the target output
175     * {@code Handler}.
176     *
177     * @param  record  description of the log event. A null record is
178     *                 silently ignored and is not published
179     */
180    @Override
181    public synchronized void publish(LogRecord record) {
182        if (!isLoggable(record)) {
183            return;
184        }
185        int ix = (start+count)%buffer.length;
186        buffer[ix] = record;
187        if (count < buffer.length) {
188            count++;
189        } else {
190            start++;
191            start %= buffer.length;
192        }
193        if (record.getLevel().intValue() >= pushLevel.intValue()) {
194            push();
195        }
196    }
197
198    /**
199     * Push any buffered output to the target {@code Handler}.
200     * <p>
201     * The buffer is then cleared.
202     */
203    public synchronized void push() {
204        for (int i = 0; i < count; i++) {
205            int ix = (start+i)%buffer.length;
206            LogRecord record = buffer[ix];
207            target.publish(record);
208        }
209        // Empty the buffer.
210        start = 0;
211        count = 0;
212    }
213
214    /**
215     * Causes a flush on the target {@code Handler}.
216     * <p>
217     * Note that the current contents of the {@code MemoryHandler}
218     * buffer are <b>not</b> written out.  That requires a "push".
219     */
220    @Override
221    public void flush() {
222        target.flush();
223    }
224
225    /**
226     * Close the {@code Handler} and free all associated resources.
227     * This will also close the target {@code Handler}.
228     *
229     * @exception  SecurityException  if a security manager exists and if
230     *             the caller does not have {@code LoggingPermission("control")}.
231     */
232    @Override
233    public void close() throws SecurityException {
234        target.close();
235        setLevel(Level.OFF);
236    }
237
238    /**
239     * Set the {@code pushLevel}.  After a {@code LogRecord} is copied
240     * into our internal buffer, if its level is greater than or equal to
241     * the {@code pushLevel}, then {@code push} will be called.
242     *
243     * @param newLevel the new value of the {@code pushLevel}
244     * @exception  SecurityException  if a security manager exists and if
245     *             the caller does not have {@code LoggingPermission("control")}.
246     */
247    public synchronized void setPushLevel(Level newLevel) throws SecurityException {
248        if (newLevel == null) {
249            throw new NullPointerException();
250        }
251        checkPermission();
252        pushLevel = newLevel;
253    }
254
255    /**
256     * Get the {@code pushLevel}.
257     *
258     * @return the value of the {@code pushLevel}
259     */
260    public Level getPushLevel() {
261        return pushLevel;
262    }
263
264    /**
265     * Check if this {@code Handler} would actually log a given
266     * {@code LogRecord} into its internal buffer.
267     * <p>
268     * This method checks if the {@code LogRecord} has an appropriate level and
269     * whether it satisfies any {@code Filter}.  However it does <b>not</b>
270     * check whether the {@code LogRecord} would result in a "push" of the
271     * buffer contents. It will return false if the {@code LogRecord} is null.
272     *
273     * @param record  a {@code LogRecord}
274     * @return true if the {@code LogRecord} would be logged.
275     *
276     */
277    @Override
278    public boolean isLoggable(LogRecord record) {
279        return super.isLoggable(record);
280    }
281}
282