Configuring Java FileHandler Logging to create directories if they do not exist

后端 未结 5 786
既然无缘
既然无缘 2020-12-17 15:45

I\'m trying to configure the Java Logging API\'s FileHandler to log my server to a file within a folder in my home directory, but I don\'t want to have to create those direc

5条回答
  •  自闭症患者
    2020-12-17 16:39

    It seems like log4j version 1.2.15 does it.

    Here is the snippet of the code which does it

    public
     synchronized
     void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)
                                                            throws IOException {
        LogLog.debug("setFile called: "+fileName+", "+append);
    
        // It does not make sense to have immediate flush and bufferedIO.
        if(bufferedIO) {
          setImmediateFlush(false);
        }
    
        reset();
        FileOutputStream ostream = null;
        try {
              //
              //   attempt to create file
              //
              ostream = new FileOutputStream(fileName, append);
        } catch(FileNotFoundException ex) {
              //
              //   if parent directory does not exist then
              //      attempt to create it and try to create file
              //      see bug 9150
              //
              String parentName = new File(fileName).getParent();
              if (parentName != null) {
                 File parentDir = new File(parentName);
                 if(!parentDir.exists() && parentDir.mkdirs()) {
                    ostream = new FileOutputStream(fileName, append);
                 } else {
                    throw ex;
                 }
              } else {
                 throw ex;
              }
        }
        Writer fw = createWriter(ostream);
        if(bufferedIO) {
          fw = new BufferedWriter(fw, bufferSize);
        }
        this.setQWForFiles(fw);
        this.fileName = fileName;
        this.fileAppend = append;
        this.bufferedIO = bufferedIO;
        this.bufferSize = bufferSize;
        writeHeader();
        LogLog.debug("setFile ended");
    }
    

    This piece of code is from FileAppender, RollingFileAppender extends FileAppender.

    Here it is not checking whether we have permission to create the parent folders, but if the parent folders is not existing then it will try to create the parent folders.

    EDITED

    If you want some additional functionalily, you can always extend RollingFileAppender and override the setFile() method.

提交回复
热议问题