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 27 package java.util.logging; 28 29 import java.io.*; 30 import java.security.AccessController; 31 import java.security.PrivilegedAction; 32 33 /** 34 * Stream based logging <tt>Handler</tt>. 35 * <p> 36 * This is primarily intended as a base class or support class to 37 * be used in implementing other logging <tt>Handlers</tt>. 38 * <p> 39 * <tt>LogRecords</tt> are published to a given <tt>java.io.OutputStream</tt>. 40 * <p> 41 * <b>Configuration:</b> 42 * By default each <tt>StreamHandler</tt> is initialized using the following 43 * <tt>LogManager</tt> configuration properties where <tt><handler-name></tt> 44 * refers to the fully-qualified class name of the handler. 45 * If properties are not defined 46 * (or have invalid values) then the specified default values are used. 47 * <ul> 48 * <li> <handler-name>.level 49 * specifies the default level for the <tt>Handler</tt> 50 * (defaults to <tt>Level.INFO</tt>). </li> 51 * <li> <handler-name>.filter 52 * specifies the name of a <tt>Filter</tt> class to use 53 * (defaults to no <tt>Filter</tt>). </li> 54 * <li> <handler-name>.formatter 55 * specifies the name of a <tt>Formatter</tt> class to use 56 * (defaults to <tt>java.util.logging.SimpleFormatter</tt>). </li> 57 * <li> <handler-name>.encoding 58 * the name of the character set encoding to use (defaults to 59 * the default platform encoding). </li> 60 * </ul> 61 * <p> 62 * For example, the properties for {@code StreamHandler} would be: 63 * <ul> 64 * <li> java.util.logging.StreamHandler.level=INFO </li> 65 * <li> java.util.logging.StreamHandler.formatter=java.util.logging.SimpleFormatter </li> 66 * </ul> 67 * <p> 68 * For a custom handler, e.g. com.foo.MyHandler, the properties would be: 69 * <ul> 70 * <li> com.foo.MyHandler.level=INFO </li> 71 * <li> com.foo.MyHandler.formatter=java.util.logging.SimpleFormatter </li> 72 * </ul> 73 * <p> 74 * @since 1.4 75 */ 76 77 public class StreamHandler extends Handler { 78 private OutputStream output; 79 private boolean doneHeader; 80 private volatile Writer writer; 81 82 // Private PrivilegedAction to configure a StreamHandler from constructor parameters, 83 // LogManager properties and/or default values as specified in the class 84 // javadoc. 85 private class ConfigureAction implements PrivilegedAction<Void> { 86 private final OutputStream out; 87 private final Formatter formatter; 88 89 ConfigureAction() { 90 this.out = null; 91 this.formatter = null; 92 } 93 94 ConfigureAction(OutputStream out, Formatter formatter) { 95 if (out == null || formatter == null) { 96 throw new NullPointerException(); 97 } 98 this.out = out; 99 this.formatter = formatter; 100 } 101 102 @Override 103 public Void run() { 104 LogManager manager = LogManager.getLogManager(); 105 String cname = StreamHandler.this.getClass().getName(); 106 107 setLevel(manager.getLevelProperty(cname +".level", Level.INFO)); 108 setFilter(manager.getFilterProperty(cname +".filter", null)); 109 setFormatter(formatter == null // use configured formatter if null 110 ? manager.getFormatterProperty(cname +".formatter", new SimpleFormatter()) 111 : formatter); 112 try { 113 setEncoding(manager.getStringProperty(cname +".encoding", null)); 114 } catch (Exception ex) { 115 try { 116 setEncoding(null); 117 } catch (Exception ex2) { 118 // doing a setEncoding with null should always work. 119 // assert false; 120 } 121 } 122 if (out != null) { // don't set output stream if null 123 setOutputStream(out); 124 } 125 return null; 126 } 127 } 128 129 /** 130 * Create a <tt>StreamHandler</tt>, with no current output stream. 131 */ 132 public StreamHandler() { 133 AccessController.doPrivileged(new ConfigureAction(), 134 null, LogManager.controlPermission); 135 } 136 137 /** 138 * Create a <tt>StreamHandler</tt> with a given <tt>Formatter</tt> 139 * and output stream. 140 * <p> 141 * @param out the target output stream 142 * @param formatter Formatter to be used to format output 143 */ 144 public StreamHandler(OutputStream out, Formatter formatter) { 145 AccessController.doPrivileged(new ConfigureAction(out, formatter), 146 null, LogManager.controlPermission); 147 } 148 149 /** 150 * Change the output stream. 151 * <P> 152 * If there is a current output stream then the <tt>Formatter</tt>'s 153 * tail string is written and the stream is flushed and closed. 154 * Then the output stream is replaced with the new output stream. 155 * 156 * @param out New output stream. May not be null. 157 * @exception SecurityException if a security manager exists and if 158 * the caller does not have <tt>LoggingPermission("control")</tt>. 159 */ 160 protected synchronized void setOutputStream(OutputStream out) throws SecurityException { 161 if (out == null) { 162 throw new NullPointerException(); 163 } 164 flushAndClose(); 165 output = out; 166 doneHeader = false; 167 String encoding = getEncoding(); 168 if (encoding == null) { 169 writer = new OutputStreamWriter(output); 170 } else { 171 try { 172 writer = new OutputStreamWriter(output, encoding); 173 } catch (UnsupportedEncodingException ex) { 174 // This shouldn't happen. The setEncoding method 175 // should have validated that the encoding is OK. 176 throw new Error("Unexpected exception " + ex); 177 } 178 } 179 } 180 181 /** 182 * Set (or change) the character encoding used by this <tt>Handler</tt>. 183 * <p> 184 * The encoding should be set before any <tt>LogRecords</tt> are written 185 * to the <tt>Handler</tt>. 186 * 187 * @param encoding The name of a supported character encoding. 188 * May be null, to indicate the default platform encoding. 189 * @exception SecurityException if a security manager exists and if 190 * the caller does not have <tt>LoggingPermission("control")</tt>. 191 * @exception UnsupportedEncodingException if the named encoding is 192 * not supported. 193 */ 194 @Override 195 public synchronized void setEncoding(String encoding) 196 throws SecurityException, java.io.UnsupportedEncodingException { 197 super.setEncoding(encoding); 198 if (output == null) { 199 return; 200 } 201 // Replace the current writer with a writer for the new encoding. 202 flush(); 203 if (encoding == null) { 204 writer = new OutputStreamWriter(output); 205 } else { 206 writer = new OutputStreamWriter(output, encoding); 207 } 208 } 209 210 /** 211 * Format and publish a <tt>LogRecord</tt>. 212 * <p> 213 * The <tt>StreamHandler</tt> first checks if there is an <tt>OutputStream</tt> 214 * and if the given <tt>LogRecord</tt> has at least the required log level. 215 * If not it silently returns. If so, it calls any associated 216 * <tt>Filter</tt> to check if the record should be published. If so, 217 * it calls its <tt>Formatter</tt> to format the record and then writes 218 * the result to the current output stream. 219 * <p> 220 * If this is the first <tt>LogRecord</tt> to be written to a given 221 * <tt>OutputStream</tt>, the <tt>Formatter</tt>'s "head" string is 222 * written to the stream before the <tt>LogRecord</tt> is written. 223 * 224 * @param record description of the log event. A null record is 225 * silently ignored and is not published 226 */ 227 @Override 228 public synchronized void publish(LogRecord record) { 229 if (!isLoggable(record)) { 230 return; 231 } 232 String msg; 233 try { 234 msg = getFormatter().format(record); 235 } catch (Exception ex) { 236 // We don't want to throw an exception here, but we 237 // report the exception to any registered ErrorManager. 238 reportError(null, ex, ErrorManager.FORMAT_FAILURE); 239 return; 240 } 241 242 try { 243 if (!doneHeader) { 244 writer.write(getFormatter().getHead(this)); 245 doneHeader = true; 246 } 247 writer.write(msg); 248 } catch (Exception ex) { 249 // We don't want to throw an exception here, but we 250 // report the exception to any registered ErrorManager. 251 reportError(null, ex, ErrorManager.WRITE_FAILURE); 252 } 253 } 254 255 256 /** 257 * Check if this <tt>Handler</tt> would actually log a given <tt>LogRecord</tt>. 258 * <p> 259 * This method checks if the <tt>LogRecord</tt> has an appropriate level and 260 * whether it satisfies any <tt>Filter</tt>. It will also return false if 261 * no output stream has been assigned yet or the LogRecord is null. 262 * <p> 263 * @param record a <tt>LogRecord</tt> 264 * @return true if the <tt>LogRecord</tt> would be logged. 265 * 266 */ 267 @Override 268 public boolean isLoggable(LogRecord record) { 269 if (writer == null || record == null) { 270 return false; 271 } 272 return super.isLoggable(record); 273 } 274 275 /** 276 * Flush any buffered messages. 277 */ 278 @Override 279 public synchronized void flush() { 280 if (writer != null) { 281 try { 282 writer.flush(); 283 } catch (Exception ex) { 284 // We don't want to throw an exception here, but we 285 // report the exception to any registered ErrorManager. 286 reportError(null, ex, ErrorManager.FLUSH_FAILURE); 287 } 288 } 289 } 290 291 private synchronized void flushAndClose() throws SecurityException { 292 checkPermission(); 293 if (writer != null) { 294 try { 295 if (!doneHeader) { 296 writer.write(getFormatter().getHead(this)); 297 doneHeader = true; 298 } 299 writer.write(getFormatter().getTail(this)); 300 writer.flush(); 301 writer.close(); 302 } catch (Exception ex) { 303 // We don't want to throw an exception here, but we 304 // report the exception to any registered ErrorManager. 305 reportError(null, ex, ErrorManager.CLOSE_FAILURE); 306 } 307 writer = null; 308 output = null; 309 } 310 } 311 312 /** 313 * Close the current output stream. 314 * <p> 315 * The <tt>Formatter</tt>'s "tail" string is written to the stream before it 316 * is closed. In addition, if the <tt>Formatter</tt>'s "head" string has not 317 * yet been written to the stream, it will be written before the 318 * "tail" string. 319 * 320 * @exception SecurityException if a security manager exists and if 321 * the caller does not have LoggingPermission("control"). 322 */ 323 @Override 324 public synchronized void close() throws SecurityException { 325 flushAndClose(); 326 } 327 }