001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018package org.apache.log4j.helpers; 019 020import java.io.Writer; 021import java.io.FilterWriter; 022import org.apache.log4j.spi.ErrorHandler; 023import org.apache.log4j.spi.ErrorCode; 024 025 026/** 027 QuietWriter does not throw exceptions when things go 028 wrong. Instead, it delegates error handling to its {@link ErrorHandler}. 029 030 @author Ceki Gülcü 031 032 @since 0.7.3 033*/ 034public class QuietWriter extends FilterWriter { 035 036 protected ErrorHandler errorHandler; 037 038 public 039 QuietWriter(Writer writer, ErrorHandler errorHandler) { 040 super(writer); 041 setErrorHandler(errorHandler); 042 } 043 044 public 045 void write(String string) { 046 if (string != null) { 047 try { 048 out.write(string); 049 } catch(Exception e) { 050 errorHandler.error("Failed to write ["+string+"].", e, 051 ErrorCode.WRITE_FAILURE); 052 } 053 } 054 } 055 056 public 057 void flush() { 058 try { 059 out.flush(); 060 } catch(Exception e) { 061 errorHandler.error("Failed to flush writer,", e, 062 ErrorCode.FLUSH_FAILURE); 063 } 064 } 065 066 067 public 068 void setErrorHandler(ErrorHandler eh) { 069 if(eh == null) { 070 // This is a programming error on the part of the enclosing appender. 071 throw new IllegalArgumentException("Attempted to set null ErrorHandler."); 072 } else { 073 this.errorHandler = eh; 074 } 075 } 076}