在Java中删除对System.out的访问 [英] Removing access to System.out in java

查看:68
本文介绍了在Java中删除对System.out的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我维护着一个应用程序,该应用程序充当多个单独程序的容器.这些程序具有自己专用的日志记录功能,即它们记录的所有内容都记录到一个特殊的日志文件中.

I maintain an application which acts as a container for multiple individual programs. These programs have their own dedicated logging facility, i.e. everything they log does to a special log file.

尽管如此,应用程序开发人员似乎全程抛出System.out.printlne.printStackTrace调用,这使得在运行容器时无法维护一个干净的控制台.

Nevertheless, application developers seem to love to throw System.out.println and e.printStackTrace calls all over, making it impossible to maintain a clean console when running the container.

如何防止这些应用程序污染System.outSystem.err?

How can I prevent these applications from polluting System.out and System.err?

实施说明:

  • 应用程序使用Log4j进行记录;
  • 该容器还使用控制台进行日志记录,但是它严格保留用于生命周期事件和问题,因此我仍然需要该控制台;
  • 使用自定义类加载器加载应用程序,但不应用安全检查.

更新:

仅重定向System.out无效,因为它会重定向所有输出,因此类似的操作会失败:

Simply redirecting System.out would not work since it redirects all output, so something like this fails:

    System.setOut(new PrintStream(new OutputStream() {

        @Override
        public void write(int b) {

            throw new Error("Not on my watch you don't");

        }
    }));

    Logger logger = Logger.getLogger(Runner.class);
    logger.info("My log message");

这应该成功.

更新2:

使用类似于以下代码的代码加载和配置应用程序

The applications are loaded and configured using code similar to

App app = new UrlClassLoader(...).loadClass(className)).newInstance();
app.setLogger(loggerForClass(app));

Log4j是从系统类加载器加载的.

Log4j is loaded from the system class loader.

推荐答案

此处的关键是在重定向输出流(例如

The key here is to configure log4j before redirecting the output streams, e.g.

BasicConfigurator.configure();
System.setOut(...);
System.setErr(...);

System.out.println("I fail");
Logger.getLogger(...).info("I work");

这篇关于在Java中删除对System.out的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆