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.BufferedOutputStream;
20  import java.io.File;
21  import java.io.FileNotFoundException;
22  import java.io.FileOutputStream;
23  import java.io.IOException;
24  import java.io.OutputStream;
25  import java.io.Serializable;
26  import java.nio.channels.FileChannel;
27  import java.nio.channels.FileLock;
28  import java.util.HashMap;
29  import java.util.Map;
30  
31  import org.apache.logging.log4j.core.Layout;
32  
33  
34  /**
35   * Manages actual File I/O for File Appenders.
36   */
37  public class FileManager extends OutputStreamManager {
38  
39      private static final FileManagerFactory FACTORY = new FileManagerFactory();
40  
41      private final boolean isAppend;
42      private final boolean isLocking;
43      private final String advertiseURI;
44  
45      protected FileManager(final String fileName, final OutputStream os, final boolean append, final boolean locking,
46                            final String advertiseURI, final Layout<? extends Serializable> layout) {
47          super(os, fileName, layout);
48          this.isAppend = append;
49          this.isLocking = locking;
50          this.advertiseURI = advertiseURI;
51      }
52  
53      /**
54       * Returns the FileManager.
55       * @param fileName The name of the file to manage.
56       * @param append true if the file should be appended to, false if it should be overwritten.
57       * @param locking true if the file should be locked while writing, false otherwise.
58       * @param bufferedIO true if the contents should be buffered as they are written.
59       * @param advertiseURI the URI to use when advertising the file
60       * @param layout The layout
61       * @param bufferSize buffer size for buffered IO
62       * @return A FileManager for the File.
63       */
64      public static FileManager getFileManager(final String fileName, final boolean append, boolean locking,
65              final boolean bufferedIO, final String advertiseURI, final Layout<? extends Serializable> layout,
66              final int bufferSize) {
67  
68          if (locking && bufferedIO) {
69              locking = false;
70          }
71          return (FileManager) getManager(fileName, new FactoryData(append, locking, bufferedIO, bufferSize,
72                  advertiseURI, layout), FACTORY);
73      }
74  
75      @Override
76      protected synchronized void write(final byte[] bytes, final int offset, final int length)  {
77  
78          if (isLocking) {
79              final FileChannel channel = ((FileOutputStream) getOutputStream()).getChannel();
80              try {
81                  /* Lock the whole file. This could be optimized to only lock from the current file
82                     position. Note that locking may be advisory on some systems and mandatory on others,
83                     so locking just from the current position would allow reading on systems where
84                     locking is mandatory.  Also, Java 6 will throw an exception if the region of the
85                     file is already locked by another FileChannel in the same JVM. Hopefully, that will
86                     be avoided since every file should have a single file manager - unless two different
87                     files strings are configured that somehow map to the same file.*/
88                  final FileLock lock = channel.lock(0, Long.MAX_VALUE, false);
89                  try {
90                      super.write(bytes, offset, length);
91                  } finally {
92                      lock.release();
93                  }
94              } catch (final IOException ex) {
95                  throw new AppenderLoggingException("Unable to obtain lock on " + getName(), ex);
96              }
97  
98          } else {
99              super.write(bytes, offset, length);
100         }
101     }
102 
103     /**
104      * Returns the name of the File being managed.
105      * @return The name of the File being managed.
106      */
107     public String getFileName() {
108         return getName();
109     }
110 
111     /**
112      * Returns the append status.
113      * @return true if the file will be appended to, false if it is overwritten.
114      */
115     public boolean isAppend() {
116         return isAppend;
117     }
118 
119     /**
120      * Returns the lock status.
121      * @return true if the file will be locked when writing, false otherwise.
122      */
123     public boolean isLocking() {
124         return isLocking;
125     }
126 
127     /**
128      * FileManager's content format is specified by: <code>Key: "fileURI" Value: provided "advertiseURI" param</code>.
129      *
130      * @return Map of content format keys supporting FileManager
131      */
132     @Override
133     public Map<String, String> getContentFormat() {
134         final Map<String, String> result = new HashMap<String, String>(super.getContentFormat());
135         result.put("fileURI", advertiseURI);
136         return result;
137     }
138 
139     /**
140      * Factory Data.
141      */
142     private static class FactoryData {
143         private final boolean append;
144         private final boolean locking;
145         private final boolean bufferedIO;
146         private final int bufferSize;
147         private final String advertiseURI;
148         private final Layout<? extends Serializable> layout;
149 
150         /**
151          * Constructor.
152          * @param append Append status.
153          * @param locking Locking status.
154          * @param bufferedIO Buffering flag.
155          * @param bufferSize Buffer size.
156          * @param advertiseURI the URI to use when advertising the file
157          */
158         public FactoryData(final boolean append, final boolean locking, final boolean bufferedIO, final int bufferSize,
159                 final String advertiseURI, final Layout<? extends Serializable> layout) {
160             this.append = append;
161             this.locking = locking;
162             this.bufferedIO = bufferedIO;
163             this.bufferSize = bufferSize;
164             this.advertiseURI = advertiseURI;
165             this.layout = layout;
166         }
167     }
168 
169     /**
170      * Factory to create a FileManager.
171      */
172     private static class FileManagerFactory implements ManagerFactory<FileManager, FactoryData> {
173 
174         /**
175          * Create a FileManager.
176          * @param name The name of the File.
177          * @param data The FactoryData
178          * @return The FileManager for the File.
179          */
180         @Override
181         public FileManager createManager(final String name, final FactoryData data) {
182             final File file = new File(name);
183             final File parent = file.getParentFile();
184             if (null != parent && !parent.exists()) {
185                 parent.mkdirs();
186             }
187 
188             OutputStream os;
189             try {
190                 os = new FileOutputStream(name, data.append);
191                 if (data.bufferedIO) {
192                     os = new BufferedOutputStream(os, data.bufferSize);
193                 }
194                 return new FileManager(name, os, data.append, data.locking, data.advertiseURI, data.layout);
195             } catch (final FileNotFoundException ex) {
196                 LOGGER.error("FileManager (" + name + ") " + ex);
197             }
198             return null;
199         }
200     }
201 
202 }