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.locks.Lock;
21  import java.util.concurrent.locks.ReadWriteLock;
22  import java.util.concurrent.locks.ReentrantReadWriteLock;
23  
24  import org.apache.logging.log4j.core.Filter;
25  import org.apache.logging.log4j.core.Layout;
26  import org.apache.logging.log4j.core.LogEvent;
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      private static final long serialVersionUID = 1L;
36  
37      /**
38       * Immediate flush means that the underlying writer or output stream will be flushed at the end of each append
39       * operation. Immediate flush is slower but ensures that each append request is actually written. If
40       * <code>immediateFlush</code> is set to {@code false}, then there is a good chance that the last few logs events
41       * are not actually written to persistent media if and when the application crashes.
42       */
43      protected final boolean immediateFlush;
44  
45      private final M manager;
46  
47      private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
48      private final Lock readLock = rwLock.readLock();
49  
50      /**
51       * Instantiate a WriterAppender and set the output destination to a new {@link java.io.OutputStreamWriter}
52       * initialized with <code>os</code> as its {@link java.io.OutputStream}.
53       * 
54       * @param name The name of the Appender.
55       * @param layout The layout to format the message.
56       * @param manager The OutputStreamManager.
57       */
58      protected AbstractOutputStreamAppender(final String name, final Layout<? extends Serializable> layout,
59              final Filter filter, final boolean ignoreExceptions, final boolean immediateFlush, final M manager) {
60          super(name, filter, layout, ignoreExceptions);
61          this.manager = manager;
62          this.immediateFlush = immediateFlush;
63      }
64  
65      /**
66       * Gets the manager.
67       * 
68       * @return the manager.
69       */
70      public M getManager() {
71          return manager;
72      }
73  
74      @Override
75      public void start() {
76          if (getLayout() == null) {
77              LOGGER.error("No layout set for the appender named [" + getName() + "].");
78          }
79          if (manager == null) {
80              LOGGER.error("No OutputStreamManager set for the appender named [" + getName() + "].");
81          }
82          super.start();
83      }
84  
85      @Override
86      public void stop() {
87          super.stop();
88          manager.release();
89      }
90  
91      /**
92       * Actual writing occurs here.
93       * <p>
94       * Most subclasses of <code>AbstractOutputStreamAppender</code> will need to override this method.
95       * </p>
96       * 
97       * @param event The LogEvent.
98       */
99      @Override
100     public void append(final LogEvent event) {
101         readLock.lock();
102         try {
103             final byte[] bytes = getLayout().toByteArray(event);
104             if (bytes.length > 0) {
105                 manager.write(bytes);
106                 if (this.immediateFlush || event.isEndOfBatch()) {
107                     manager.flush();
108                 }
109             }
110         } catch (final AppenderLoggingException ex) {
111             error("Unable to write to stream " + manager.getName() + " for appender " + getName());
112             throw ex;
113         } finally {
114             readLock.unlock();
115         }
116     }
117 }