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.IOException;
20  import java.io.Writer;
21  
22  import org.apache.logging.log4j.core.StringLayout;
23  
24  /**
25   * Manages a Writer so that it can be shared by multiple Appenders and will
26   * allow appenders to reconfigure without requiring a new writer.
27   */
28  public class WriterManager extends AbstractManager {
29  
30      /**
31       * Creates a Manager.
32       *
33       * @param name The name of the stream to manage.
34       * @param data The data to pass to the Manager.
35       * @param factory The factory to use to create the Manager.
36       * @param <T> The type of the WriterManager.
37       * @return A WriterManager.
38       */
39      public static <T> WriterManager getManager(final String name, final T data,
40                                                   final ManagerFactory<? extends WriterManager, T> factory) {
41          return AbstractManager.getManager(name, factory, data);
42      }
43      protected final StringLayout layout;
44  
45      private volatile Writer writer;
46  
47      public WriterManager(final Writer writer, final String streamName, final StringLayout layout,
48              final boolean writeHeader) {
49          super(streamName);
50          this.writer = writer;
51          this.layout = layout;
52          if (writeHeader && layout != null) {
53              final byte[] header = layout.getHeader();
54              if (header != null) {
55                  try {
56                      this.writer.write(new String(header, layout.getCharset()));
57                  } catch (final IOException e) {
58                      logError("Unable to write header", e);
59                  }
60              }
61          }
62      }
63  
64      protected synchronized void close() {
65          final Writer w = writer; // access volatile field only once per method
66          try {
67              w.close();
68          } catch (final IOException ex) {
69              logError("Unable to close stream", ex);
70          }
71      }
72  
73      /**
74       * Flushes any buffers.
75       */
76      public synchronized void flush() {
77          try {
78              writer.flush();
79          } catch (final IOException ex) {
80              final String msg = "Error flushing stream " + getName();
81              throw new AppenderLoggingException(msg, ex);
82          }
83      }
84  
85      protected Writer getWriter() {
86          return writer;
87      }
88  
89      /**
90       * Returns the status of the stream.
91       * @return true if the stream is open, false if it is not.
92       */
93      public boolean isOpen() {
94          return getCount() > 0;
95      }
96  
97      /**
98       * Default hook to write footer during close.
99       */
100     @Override
101     public void releaseSub() {
102         writeFooter();
103         close();
104     }
105 
106     protected void setWriter(final Writer writer) {
107         final byte[] header = layout.getHeader();
108         if (header != null) {
109             try {
110                 writer.write(new String(header, layout.getCharset()));
111                 this.writer = writer; // only update field if writer.write() succeeded
112             } catch (final IOException ioe) {
113                 logError("Unable to write header", ioe);
114             }
115         } else {
116             this.writer = writer;
117         }
118     }
119 
120     /**
121      * Some output streams synchronize writes while others do not. Synchronizing here insures that
122      * log events won't be intertwined.
123      * @param bytes The serialized Log event.
124      * @param offset The offset into the byte array.
125      * @param length The number of bytes to write.
126      * @throws AppenderLoggingException if an error occurs.
127      */
128     protected synchronized void write(final String str)  {
129         try {
130             writer.write(str);
131         } catch (final IOException ex) {
132             final String msg = "Error writing to stream " + getName();
133             throw new AppenderLoggingException(msg, ex);
134         }
135     }
136 
137     /**
138      * Writes the footer.
139      */
140     protected void writeFooter() {
141         if (layout == null) {
142             return;
143         }
144         final byte[] footer = layout.getFooter();
145         if (footer != null && footer.length > 0) {
146             write(new String(footer, layout.getCharset()));
147         }
148     }
149 }