2

As the title of the question states, is it possible to avoid creating parent folders of log4j2 File appender log file if they don't exist? Actually, when I pass the non-existing parent folder of the file appender log it will be created automatically by log4j2. I have already tried to see if there is an attribute on the File tag but there is nothing.

https://logging.apache.org/log4j/2.x/manual/appenders.html

<Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout
                pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
        <File name="File" fileName="${sys:app.home}/app.log"
            ignoreExceptions="false">
            <PatternLayout
                pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </File>
</Appenders>
6
  • That seems like an odd goal - what would you have it do instead, fail? It shouldn't be hard to check for this situation before invoking it. Commented Dec 30, 2018 at 0:40
  • I would like it to fail if it doesn't find the parent folder, or simply do nothing. Commented Dec 30, 2018 at 0:44
  • Are you specifying a logging.path flag somewhere in your program? Commented Dec 30, 2018 at 0:51
  • @kirishna do you mean fileName="${sys:app.home}/app.log" from above. Commented Dec 30, 2018 at 0:54
  • No, apart from that. I use logback in spring boot and if I want it to fail, I specify the logging.path flag (which is in the properties file) with a folder that should exist. Do you use a framework? Commented Dec 30, 2018 at 1:03

1 Answer 1

1

There is no such option. Here is source code of FileAppender where you can see creating of parent folder. If you want to avoid creating folder then you can create your own inheritor of FileAppender and override setFile method.

public synchronized void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)
                                                        throws IOException {
....
FileOutputStream ostream = null;
try {
      ostream = new FileOutputStream(fileName, append);
} catch(FileNotFoundException ex) {
   String parentName = new File(fileName).getParent();
      if (parentName != null) {
         File parentDir = new File(parentName); 
         if(!parentDir.exists() && parentDir.mkdirs()) { //This is were parent folders are created
            ostream = new FileOutputStream(fileName, append);
         } else {
            throw ex;
         }
      } else {
         throw ex;
      }
}
....
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.