๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

์„œ๋ฒ„์—์„œ ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ค๊ธฐ -์ž‘์„ฑ์ค‘-

์‹œํ๋ฆฌํ‹ฐ์ง€ํ˜ธ 2024. 8. 20.

package com.example.logreader.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

@RestController
@RequestMapping("/logs")
public class LogController {

    private static final String LOG_FILE_PATH = "/path/to/your/logfile.log";

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadLogFile() {
        File file = new File(LOG_FILE_PATH);
        if (file.exists()) {
            Resource resource = new FileSystemResource(file);
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
                    .body(resource);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

    @GetMapping("/view")
    public ResponseEntity<List<String>> viewLogFile() {
        try {
            List<String> logLines = Files.readAllLines(new File(LOG_FILE_PATH).toPath());
            return ResponseEntity.ok(logLines);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
}

 

 

  • ๋กœ๊ทธ ํŒŒ์ผ ๋‹ค์šด๋กœ๋“œ: http://localhost:8080/logs/download
  • ๋กœ๊ทธ ํŒŒ์ผ ๋‚ด์šฉ ๋ณด๊ธฐ: http://localhost:8080/logs/view

 

๋Œ“๊ธ€