package com.xqx.bdcbsdt.controller;
import com.xqx.bdcbsdt.common.Response;
import com.xqx.bdcbsdt.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.regex.Pattern;
/**
* 管理后台下载log文件
*/
@Slf4j
@Controller
public class LogFileController {
@Value("${logging.file.path}")
private String logFilePath=null;
@Value("${logging.file.name}")
private String logFileName=null;
@GetMapping("/admin/logfile")
public String index(ModelMap modelMap){
Map logfile=new LinkedHashMap();
String[] split = logFileName.split("/");
String logName=split[split.length-1];
File file=new File(logFilePath);
if (!file.isFile()){
File[] files = file.listFiles();
Arrays.stream(files).forEach(temp->{
if (temp.isFile()&& temp.exists()) {
logfile.put(temp.getName(),temp.getAbsolutePath());
}
});
}
Map sortMap=new LinkedHashMap();
sortMap.put(logName,logfile.get(logName));
logfile.remove(logName);
sortMap.putAll(logfile);
modelMap.put("files",sortMap);
return "logfile/index";
}
@ResponseBody
@RequestMapping("/admin/logfile/delete/{filename}")
public Response deleteLogFile(@PathVariable String filename){
File file = new File(logFilePath +'/'+ filename);
//消除系统分隔符差异
String tempLogName=logFileName.replace("/",File.separator).replace("\\",File.separator);
if (file.exists()){
if (tempLogName.equalsIgnoreCase(file.getPath())){
return Response.error("当日log文件不允许删除!");
}
return file.delete()?Response.success("删除成功!",null):Response.error("删除失败!");
}
return Response.error("文件不存在!");
}
@RequestMapping("/admin/logfile/{filename}")
public void downloadLogFile(HttpServletResponse response, @PathVariable String filename) throws Exception{
File file = new File(logFilePath +'/'+ filename);
if(!file.exists()){
return;
}
response.reset();
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
byte[] buff = new byte[1024];
OutputStream os = response.getOutputStream();
int i = 0;
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
os.flush();
}
} catch (IOException e) {
log.error("{}",e);
}
}
}
Java 程序日志下载
于 2023-08-24 17:29:03 首次发布