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  
21  import org.apache.logging.log4j.core.Filter;
22  import org.apache.logging.log4j.core.Layout;
23  import org.apache.logging.log4j.core.LogEvent;
24  import org.apache.logging.log4j.core.util.Constants;
25  
26  /**
27   * Appends log events as bytes to a byte output stream. The stream encoding is defined in the layout.
28   *
29   * @param <M> The kind of {@link OutputStreamManager} under management
30   */
31  public abstract class AbstractOutputStreamAppender<M extends OutputStreamManager> extends AbstractAppender {
32  
33      /**
34       * Immediate flush means that the underlying writer or output stream will be flushed at the end of each append
35       * operation. Immediate flush is slower but ensures that each append request is actually written. If
36       * <code>immediateFlush</code> is set to {@code false}, then there is a good chance that the last few logs events
37       * are not actually written to persistent media if and when the application crashes.
38       */
39      private final boolean immediateFlush;
40  
41      private final M manager;
42  
43      /**
44       * Instantiates a WriterAppender and set the output destination to a new {@link java.io.OutputStreamWriter}
45       * initialized with <code>os</code> as its {@link java.io.OutputStream}.
46       *
47       * @param name The name of the Appender.
48       * @param layout The layout to format the message.
49       * @param manager The OutputStreamManager.
50       */
51      protected AbstractOutputStreamAppender(final String name, final Layout<? extends Serializable> layout,
52              final Filter filter, final boolean ignoreExceptions, final boolean immediateFlush, final M manager) {
53          super(name, filter, layout, ignoreExceptions);
54          this.manager = manager;
55          this.immediateFlush = immediateFlush;
56      }
57  
58      /**
59       * Gets the immediate flush setting.
60       *
61       * @return immediate flush.
62       */
63      public boolean getImmediateFlush() {
64          return immediateFlush;
65      }
66  
67      /**
68       * Gets the manager.
69       *
70       * @return the manager.
71       */
72      public M getManager() {
73          return manager;
74      }
75  
76      @Override
77      public void start() {
78          if (getLayout() == null) {
79              LOGGER.error("No layout set for the appender named [" + getName() + "].");
80          }
81          if (manager == null) {
82              LOGGER.error("No OutputStreamManager set for the appender named [" + getName() + "].");
83          }
84          super.start();
85      }
86  
87      @Override
88      public void stop() {
89          super.stop();
90          manager.release();
91      }
92  
93      /**
94       * Actual writing occurs here.
95       * <p>
96       * Most subclasses of <code>AbstractOutputStreamAppender</code> will need to override this method.
97       * </p>
98       *
99       * @param event The LogEvent.
100      */
101     @Override
102     public void append(final LogEvent event) {
103         try {
104             tryAppend(event);
105         } catch (final AppenderLoggingException ex) {
106             error("Unable to write to stream " + manager.getName() + " for appender " + getName() + ": " + ex);
107             throw ex;
108         }
109     }
110 
111     private void tryAppend(final LogEvent event) {
112         if (Constants.ENABLE_DIRECT_ENCODERS) {
113             directEncodeEvent(event);
114         } else {
115             writeByteArrayToManager(event);
116         }
117     }
118 
119     protected void directEncodeEvent(final LogEvent event) {
120         getLayout().encode(event, manager);
121         if (this.immediateFlush || event.isEndOfBatch()) {
122             manager.flush();
123         }
124     }
125 
126     protected void writeByteArrayToManager(final LogEvent event) {
127         final byte[] bytes = getLayout().toByteArray(event);
128         if (bytes != null && bytes.length > 0) {
129             manager.write(bytes, this.immediateFlush || event.isEndOfBatch());
130         }
131     }
132 }