0

有什么办法可以将控制台输出镜像到java中的localhost,甚至可以添加一些不错的CSS。如果同一网络中的其他设备也可以访问控制台,那就太酷了。我对这个主题做了很多研究,但没有找到任何关于这个的网站/线程/问题。帮助将不胜感激!

4

2 回答 2

1

为了拦截通常进入控制台(或标准输出)的输出,您需要在代码中的某处使用以下 API:

System.setOut(myStream); 
System.setErr(myStream); //If you want to grab the error stream also. Could go do a different location

许多日志库已经可以为您做到这一点。但这基本上是您需要捕获输出的方式。'myStream' 的实际作用取决于您。将其输出到 http://localhost:8888 上的 Web 服务器的最快方法是将输出定向到文件并启动 JDK 的嵌入式 Web 服务器。这是您应该能够运行的示例:

package test.example;

import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;

import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class SystemOutToWeb
{
    public static void main(String... args ) throws Exception
    {
        final Path myOutputFile = Paths.get("./MyOutputFile.txt");
        final PrintStream myStream = new PrintStream(myOutputFile.toFile());

        System.out.println("Going to redirect to : " + myOutputFile.toAbsolutePath());

        System.setOut(myStream);
        System.setErr(myStream);

        System.out.println("Starting the Output");

        //Have something that logs every 5 seconds
        final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(() ->
        {
            System.out.println("Hello - the time is now " + Instant.now());
        }, 1, 5, TimeUnit.SECONDS);

        // Start the simple Java Built in Web Server.
        final HttpServer http = HttpServer.create(new InetSocketAddress(8888), 0);
        final HttpContext context = http.createContext("/");
        context.setHandler(exchange ->
        {
            byte[] data = Files.readAllBytes(myOutputFile);
            exchange.sendResponseHeaders(200, data.length);
            OutputStream os = exchange.getResponseBody();
            os.write(data);
            os.close();
        });
        http.start();

    }
}

如果你让它运行几秒钟,那么你应该能够在 http://localhost:8888 看到一些东西。

当然,这只是起点。例如,您可以一起使用不同的 Web 服务器或使用一些 CSS 进一步扩充此资源(甚至可能使用 Web 套接字在文件更新时将其流式传输)。

于 2021-12-31T11:05:14.953 回答
0

你想要像集中式日志这样的东西吗?有像 Grafana Loki 这样的工具,您可以使用名为 promtail 的日志收集器从文件中收集日志并将它们发送到您的 Loki 实例,并且使用 Grafana 前端您可以获得可搜索的彩色日志。这可以包括来自多个应用程序的日志。

https://grafana.com/docs/loki/latest/clients/promtail/

你可以将它发送到 Grafana Cloud,它可以为最多三个用户提供免费套餐,或者使用 docker 托管 Grafana Stack,这是一个可以使用的堆栈:

https://github.com/stefanprodan/dockprom

于 2021-12-31T14:40:38.067 回答