在 Spring Web 应用程序中(尽管我认为这与 Spring 无关),我创建了一个 REST GET 资源,它允许下载当前的 log4j2 文件内容,但是请求(来自浏览器和 cUrl)不会以webapp 部署在远程生产服务器上——而它们通常在我的 Windows 开发机器上结束。
此外,cUrl 说还有字节要接收:
* transfer closed with 3 bytes remaining to read
* stopped the pause stream!
* Closing connection 0
curl: (18) transfer closed with 3 bytes remaining to read
这是相关代码:
// ...
import org.springframework.http.HttpHeaders;
// ...
@RestController
@RequestMapping(path="/logs", produces="application/json")
public class LogController {
// ...
@GetMapping(path="/{appenderName}/contents", produces="text/plain")
public void download(@PathVariable String appenderName, HttpServletResponse response) {
// ...
org.apache.logging.log4j.Logger rootLogger = LogManager.getRootLogger();
if(rootLogger instanceof Logger) {
Logger l = (Logger) rootLogger;
if(l.getAppenders().containsKey(appenderName)) {
Appender appender = l.getAppenders().get(appenderName);
if(appender instanceof FileAppender) {
((FileAppender) appender).getManager().flush();
final File f = new File(((FileAppender) appender).getFileName());
response.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + f.getName() + "\"");
Path tempCopy = Files.createTempFile("log-", null);
Files.copy(f.toPath(), tempCopy, StandardCopyOption.REPLACE_EXISTING);
我认为问题出在Content-length标题上:在 Linux (Ubuntu) 服务器上,只有当我减去3文件长度时才有效:
response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(tempCopy.toFile().length() - 3));
我尝试在下载前将原始文件复制到临时文件,但似乎没有帮助。
当然,如果我不发送任何Content-Length标题,一切都很好。
动漫人物
慕少森
相关分类