Path: blob/master/src/java.logging/share/classes/java/util/logging/StreamHandler.java
41159 views
/*1* Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/242526package java.util.logging;2728import java.io.*;29import java.security.AccessController;30import java.security.PrivilegedAction;31import java.util.Objects;3233/**34* Stream based logging {@code Handler}.35* <p>36* This is primarily intended as a base class or support class to37* be used in implementing other logging {@code Handlers}.38* <p>39* {@code LogRecords} are published to a given {@code java.io.OutputStream}.40* <p>41* <b>Configuration:</b>42* By default each {@code StreamHandler} is initialized using the following43* {@code LogManager} configuration properties where {@code <handler-name>}44* refers to the fully-qualified class name of the handler.45* If properties are not defined46* (or have invalid values) then the specified default values are used.47* <ul>48* <li> <handler-name>.level49* specifies the default level for the {@code Handler}50* (defaults to {@code Level.INFO}). </li>51* <li> <handler-name>.filter52* specifies the name of a {@code Filter} class to use53* (defaults to no {@code Filter}). </li>54* <li> <handler-name>.formatter55* specifies the name of a {@code Formatter} class to use56* (defaults to {@code java.util.logging.SimpleFormatter}). </li>57* <li> <handler-name>.encoding58* the name of the character set encoding to use (defaults to59* 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*74* @since 1.475*/7677public class StreamHandler extends Handler {78private OutputStream output;79private boolean doneHeader;80private volatile Writer writer;8182/**83* Create a {@code StreamHandler}, with no current output stream.84*/85public StreamHandler() {86// configure with specific defaults for StreamHandler87super(Level.INFO, new SimpleFormatter(), null);88}8990/**91* Create a {@code StreamHandler} with a given {@code Formatter}92* and output stream.93*94* @param out the target output stream95* @param formatter Formatter to be used to format output96*/97public StreamHandler(OutputStream out, Formatter formatter) {98// configure with default level but use specified formatter99super(Level.INFO, null, Objects.requireNonNull(formatter));100101setOutputStreamPrivileged(out);102}103104/**105* @see Handler#Handler(Level, Formatter, Formatter)106*/107StreamHandler(Level defaultLevel,108Formatter defaultFormatter,109Formatter specifiedFormatter) {110super(defaultLevel, defaultFormatter, specifiedFormatter);111}112113/**114* Change the output stream.115* <P>116* If there is a current output stream then the {@code Formatter}'s117* tail string is written and the stream is flushed and closed.118* Then the output stream is replaced with the new output stream.119*120* @param out New output stream. May not be null.121* @throws SecurityException if a security manager exists and if122* the caller does not have {@code LoggingPermission("control")}.123*/124protected synchronized void setOutputStream(OutputStream out) throws SecurityException {125if (out == null) {126throw new NullPointerException();127}128flushAndClose();129output = out;130doneHeader = false;131String encoding = getEncoding();132if (encoding == null) {133writer = new OutputStreamWriter(output);134} else {135try {136writer = new OutputStreamWriter(output, encoding);137} catch (UnsupportedEncodingException ex) {138// This shouldn't happen. The setEncoding method139// should have validated that the encoding is OK.140throw new Error("Unexpected exception " + ex);141}142}143}144145/**146* Set (or change) the character encoding used by this {@code Handler}.147* <p>148* The encoding should be set before any {@code LogRecords} are written149* to the {@code Handler}.150*151* @param encoding The name of a supported character encoding.152* May be null, to indicate the default platform encoding.153* @throws SecurityException if a security manager exists and if154* the caller does not have {@code LoggingPermission("control")}.155* @throws UnsupportedEncodingException if the named encoding is156* not supported.157*/158@Override159public synchronized void setEncoding(String encoding)160throws SecurityException, java.io.UnsupportedEncodingException {161super.setEncoding(encoding);162if (output == null) {163return;164}165// Replace the current writer with a writer for the new encoding.166flush();167if (encoding == null) {168writer = new OutputStreamWriter(output);169} else {170writer = new OutputStreamWriter(output, encoding);171}172}173174/**175* Format and publish a {@code LogRecord}.176* <p>177* The {@code StreamHandler} first checks if there is an {@code OutputStream}178* and if the given {@code LogRecord} has at least the required log level.179* If not it silently returns. If so, it calls any associated180* {@code Filter} to check if the record should be published. If so,181* it calls its {@code Formatter} to format the record and then writes182* the result to the current output stream.183* <p>184* If this is the first {@code LogRecord} to be written to a given185* {@code OutputStream}, the {@code Formatter}'s "head" string is186* written to the stream before the {@code LogRecord} is written.187*188* @param record description of the log event. A null record is189* silently ignored and is not published190*/191@Override192public synchronized void publish(LogRecord record) {193if (!isLoggable(record)) {194return;195}196String msg;197try {198msg = getFormatter().format(record);199} catch (Exception ex) {200// We don't want to throw an exception here, but we201// report the exception to any registered ErrorManager.202reportError(null, ex, ErrorManager.FORMAT_FAILURE);203return;204}205206try {207if (!doneHeader) {208writer.write(getFormatter().getHead(this));209doneHeader = true;210}211writer.write(msg);212} catch (Exception ex) {213// We don't want to throw an exception here, but we214// report the exception to any registered ErrorManager.215reportError(null, ex, ErrorManager.WRITE_FAILURE);216}217}218219220/**221* Check if this {@code Handler} would actually log a given {@code LogRecord}.222* <p>223* This method checks if the {@code LogRecord} has an appropriate level and224* whether it satisfies any {@code Filter}. It will also return false if225* no output stream has been assigned yet or the LogRecord is null.226*227* @param record a {@code LogRecord} (may be null).228* @return true if the {@code LogRecord} would be logged.229*230*/231@Override232public boolean isLoggable(LogRecord record) {233if (writer == null || record == null) {234return false;235}236return super.isLoggable(record);237}238239/**240* Flush any buffered messages.241*/242@Override243public synchronized void flush() {244if (writer != null) {245try {246writer.flush();247} catch (Exception ex) {248// We don't want to throw an exception here, but we249// report the exception to any registered ErrorManager.250reportError(null, ex, ErrorManager.FLUSH_FAILURE);251}252}253}254255private synchronized void flushAndClose() throws SecurityException {256checkPermission();257if (writer != null) {258try {259if (!doneHeader) {260writer.write(getFormatter().getHead(this));261doneHeader = true;262}263writer.write(getFormatter().getTail(this));264writer.flush();265writer.close();266} catch (Exception ex) {267// We don't want to throw an exception here, but we268// report the exception to any registered ErrorManager.269reportError(null, ex, ErrorManager.CLOSE_FAILURE);270}271writer = null;272output = null;273}274}275276/**277* Close the current output stream.278* <p>279* The {@code Formatter}'s "tail" string is written to the stream before it280* is closed. In addition, if the {@code Formatter}'s "head" string has not281* yet been written to the stream, it will be written before the282* "tail" string.283*284* @throws SecurityException if a security manager exists and if285* the caller does not have LoggingPermission("control").286*/287@Override288public synchronized void close() throws SecurityException {289flushAndClose();290}291292// Package-private support for setting OutputStream293// with elevated privilege.294@SuppressWarnings("removal")295final void setOutputStreamPrivileged(final OutputStream out) {296AccessController.doPrivileged(new PrivilegedAction<Void>() {297@Override298public Void run() {299setOutputStream(out);300return null;301}302}, null, LogManager.controlPermission);303}304}305306307