View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.appender;
18  
19  import java.io.Serializable;
20  import java.util.concurrent.TimeUnit;
21  
22  import org.apache.logging.log4j.core.Filter;
23  import org.apache.logging.log4j.core.Layout;
24  import org.apache.logging.log4j.core.LogEvent;
25  import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute;
26  import org.apache.logging.log4j.core.util.Constants;
27  
28  /**
29   * Appends log events as bytes to a byte output stream. The stream encoding is defined in the layout.
30   *
31   * @param <M> The kind of {@link OutputStreamManager} under management
32   */
33  public abstract class AbstractOutputStreamAppender<M extends OutputStreamManager> extends AbstractAppender {
34  
35      /**
36       * Subclasses can extend this abstract Builder. 
37       * 
38       * @param <B> This builder class.
39       */
40      public abstract static class Builder<B extends Builder<B>> extends AbstractAppender.Builder<B> {
41      
42          @PluginBuilderAttribute
43          private boolean bufferedIo = true;
44  
45          @PluginBuilderAttribute
46          private int bufferSize = Constants.ENCODER_BYTE_BUFFER_SIZE;
47  
48          @PluginBuilderAttribute
49          private boolean immediateFlush = true;
50  
51          public int getBufferSize() {
52              return bufferSize;
53          }
54  
55          public boolean isBufferedIo() {
56              return bufferedIo;
57          }
58  
59          public boolean isImmediateFlush() {
60              return immediateFlush;
61          }
62          
63          public B withImmediateFlush(final boolean immediateFlush) {
64              this.immediateFlush = immediateFlush;
65              return asBuilder();
66          }
67          
68          public B withBufferedIo(final boolean bufferedIo) {
69              this.bufferedIo = bufferedIo;
70              return asBuilder();
71          }
72  
73          public B withBufferSize(final int bufferSize) {
74              this.bufferSize = bufferSize;
75              return asBuilder();
76          }
77  
78      }
79      
80      /**
81       * Immediate flush means that the underlying writer or output stream will be flushed at the end of each append
82       * operation. Immediate flush is slower but ensures that each append request is actually written. If
83       * <code>immediateFlush</code> is set to {@code false}, then there is a good chance that the last few logs events
84       * are not actually written to persistent media if and when the application crashes.
85       */
86      private final boolean immediateFlush;
87  
88      private final M manager;
89  
90      /**
91       * Instantiates a WriterAppender and set the output destination to a new {@link java.io.OutputStreamWriter}
92       * initialized with <code>os</code> as its {@link java.io.OutputStream}.
93       *
94       * @param name The name of the Appender.
95       * @param layout The layout to format the message.
96       * @param manager The OutputStreamManager.
97       */
98      protected AbstractOutputStreamAppender(final String name, final Layout<? extends Serializable> layout,
99              final Filter filter, final boolean ignoreExceptions, final boolean immediateFlush, final M manager) {
100         super(name, filter, layout, ignoreExceptions);
101         this.manager = manager;
102         this.immediateFlush = immediateFlush;
103     }
104 
105     /**
106      * Gets the immediate flush setting.
107      *
108      * @return immediate flush.
109      */
110     public boolean getImmediateFlush() {
111         return immediateFlush;
112     }
113 
114     /**
115      * Gets the manager.
116      *
117      * @return the manager.
118      */
119     public M getManager() {
120         return manager;
121     }
122 
123     @Override
124     public void start() {
125         if (getLayout() == null) {
126             LOGGER.error("No layout set for the appender named [" + getName() + "].");
127         }
128         if (manager == null) {
129             LOGGER.error("No OutputStreamManager set for the appender named [" + getName() + "].");
130         }
131         super.start();
132     }
133 
134     @Override
135     public boolean stop(final long timeout, final TimeUnit timeUnit) {
136         return stop(timeout, timeUnit, true);
137     }
138 
139     @Override
140     protected boolean stop(final long timeout, final TimeUnit timeUnit, final boolean changeLifeCycleState) {
141         boolean stopped = super.stop(timeout, timeUnit, changeLifeCycleState);
142         stopped &= manager.stop(timeout, timeUnit);
143         if (changeLifeCycleState) {
144             setStopped();
145         }
146         return stopped;
147     }
148 
149     /**
150      * Actual writing occurs here.
151      * <p>
152      * Most subclasses of <code>AbstractOutputStreamAppender</code> will need to override this method.
153      * </p>
154      *
155      * @param event The LogEvent.
156      */
157     @Override
158     public void append(final LogEvent event) {
159         try {
160             tryAppend(event);
161         } catch (final AppenderLoggingException ex) {
162             error("Unable to write to stream " + manager.getName() + " for appender " + getName() + ": " + ex);
163             throw ex;
164         }
165     }
166 
167     private void tryAppend(final LogEvent event) {
168         if (Constants.ENABLE_DIRECT_ENCODERS) {
169             directEncodeEvent(event);
170         } else {
171             writeByteArrayToManager(event);
172         }
173     }
174 
175     protected void directEncodeEvent(final LogEvent event) {
176         getLayout().encode(event, manager);
177         if (this.immediateFlush || event.isEndOfBatch()) {
178             manager.flush();
179         }
180     }
181 
182     protected void writeByteArrayToManager(final LogEvent event) {
183         final byte[] bytes = getLayout().toByteArray(event);
184         if (bytes != null && bytes.length > 0) {
185             manager.write(bytes, this.immediateFlush || event.isEndOfBatch());
186         }
187     }
188 }