How to use timestamp in spring boot property file?

Viewed 756

I want to use restart timestamp in log file name, can I get it somehow in properties file?

Current implementation:

logging.file.name=abc_services-${PID}.log

Something like below should be helpful:

logging.file.name=abc_services-${PID}-${timestamp}.log

Other ways to achieve are:

  1. Using system property LOG_FILE and set file name having timestamp
  2. Using logback-spring.xml file and use the way explained in this answer.

But achieving this in property file is what I find nice approach. Spring boot version 2.6.5

2 Answers

I prefer the standard spring logback xml mechanism as you have mentioned in your question.

I tried following with latest demo spring web project from https://start.spring.io/

  1. I followed Add Timestamp Variable to Folder Path Value in Application Properties. At startup I set the timestamp and accessed the same in properties. But this will fix the file name till server restarts.

example filename: abc_services-52855-1648696549862.log

I set the timestamp variable as below. We can control the format as required and there are multiple ways to set the environment variable.

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
    System.setProperty("timestamp",String.valueOf(System.currentTimeMillis()));

    SpringApplication.run(DemoApplication.class, args);
    }
}
  1. Instead of generating custome time stamp we can use maven build timestamp

    logging.file.name=abc_services-${PID}-@maven.build.timestamp@.log

  2. If application running in Docker/Cloud environment/Container, it should have an environment variable storing the startup time. We can use that time stamp to define the timestamp in file names

The intended way here is probably to use a logback.xml with an appropriate FileNamePattern as described here.

Related