'Spring Boot Creating endpoint for download logs

I created an endpoint in spring boot to download logs of the application:

@Service
public class LogService {

    public byte[] obterLog() {

        try {
            InputStream inputStream = new ClassPathResource("spring.log").getInputStream();

            byte[] log = FileCopyUtils.copyToByteArray(inputStream);

            return log;

        } catch (IOException e) {
            throw new FileException(e.getMessage());
        }
    }

And the controller

@Autowired
private LogService logService;

@GetMapping
public ResponseEntity<byte[]> getLog() {
    byte[] log = logService.obterLog();

    return ResponseEntity.ok().body(log);
}

But I can only get the log on the second time that I run the application and the log file is on the target/classes folder.

On the first time that I run the application I get a exception:

Class path resource [spring.log] cannot be opened because it does not exist

Why is this happening?



Solution 1:[1]

Yes the exception is right. When there are logs, it start printing into .log file and if it is not there, it will create one. In your case you could log something in when the app starts.

You could try something like this and see if the file exist and log something and then try again.

Path path = Paths.get("/path/to/spring.log");

// file exists and it is not a directory
if(Files.exists(path) && !Files.isDirectory(path)) {
    log.info("file created");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zoe stands with Ukraine