0

I have a final static logger object, this is created when the main method is first executed. If the log file is not there it is created and then appended to (using the log4j API, appender). However I want to check that the machine that the application is run on has the directory created that the application is due to save into.

The problem is that this folder check/creation needs to happen before the log is created and the log is created on class instantiation. I s there a standard way to deal with this issue, I want to avoid re-placing all the logging statements so keeping the logger static is preferable?

Jas
  • 3,207
  • 2
  • 15
  • 45
John Paul
  • 772
  • 1
  • 6
  • 17

1 Answers1

1

You can use a static initializer to achieve this:

public class Foo {
    static {
        //check the directory
        //initialize the logger
    }
}

This static initalizer will run when the class is loaded. So there you can check if the directory exists before you actually create the logger.

Community
  • 1
  • 1
David Tanzer
  • 2,732
  • 18
  • 30
  • That worked well, thanks, it ended up as; public class Main { static Logger log; static{ String dir = "C:"+File.separator+"apslive"+File.separator+"SWQRImageExtraction"; //TODO File file = new File(dir); if(!file.exists()){ if(file.mkdir()){ System.out.println("Directory Created: "+dir); }else{ System.out.println("Failed to create directory"); } } log = Logger.getLogger(Main.class); } ... } – John Paul Nov 19 '15 at 12:57