0

We have a static java.util.logging.Logger variable as myLogger. Currently, it prints only to console so we have to add FileHandler to it. The project is Profile based so depending on the profile specified at the compile time, appropriate application-{profile}.properties file will be loaded. This file has different log file location for each profile.

How can a FileHandler be instantiated with value from application.properties?

Code snippet:

private static String logFileName;
@Value("${loggingSftp.logFileName}")
public void setLogFileName(String logFileName) {
    SftpConfiguration.logFileName = logFileName;
}

private static final Logger LOGGER = Logger.getLogger(SftpConfiguration.class.getPackage().getName());

private static FileHandler fileHandler;

static {
    try {
        LOGGER.info("log file name: " + logFileName);
        fileHandler = new FileHandler(LoggingFileHandler.getLogFileName()
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyMMdd")));
        LOGGER.addHandler(fileHandler);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Now, logFileName is 'null' when static block is initializing and adding fileHandler.

Nets
  • 95
  • 2
  • 11

1 Answers1

0

What is happening is the static block executes before your properties are loaded.

You need to move the static block into a @PostConstruct method so all of your injected values are present. Then lookup your property values from within that @PostConstruct method.

jmehrens
  • 10,580
  • 1
  • 38
  • 47