如何从Java中的生产代码中删除调试语句 [英] How to remove debug statements from production code in Java

查看:125
本文介绍了如何从Java中的生产代码中删除调试语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译器可以从生产代码中删除用于调试目的的语句(例如日志记录)吗?调试语句需要以某种方式标记,可能使用注释。

Is it possible for the compiler to remove statements used for debugging purposes (such as logging) from production code? The debug statements would need to be marked somehow, maybe using annotations.

很容易设置一个属性(debug = true),并在每个调试语句可以降低性能。

It's easy to set a property (debug = true) and check it at each debug statement, but this can reduce performance. It would be nice if the compiler would simply make the debug statements vanish.

推荐答案

两个建议。

第一:
用于实际日志记录,使用现代日志记录包,如log4j或java自己内置的日志记录。不要担心性能这么多,日志记录级别检查是纳秒的量级。 (它是一个整数比较)。

First: for real logging, use a modern logging package like log4j or java's own built in logging. Don't worry about performance so much, the logging level check is on the order of nanoseconds. (it's an integer comparison).

如果你有一个以上的日志语句,保护整个块:

And if you have more than a single log statement, guard the whole block:

(log4j,例如:)

(log4j, for example:)

if (logger.isDebugEnabled()) {

  // perform expensive operations
  // build string to log

  logger.debug("....");
}

这将在运行时添加能力控制日志记录。必须重新启动并运行调试版本可能非常不方便。

This gives you the added ability control logging at runtime. Having to restart and run a debug build can be very inconvenient.

第二个

您可能会发现断言更多你需要什么。断言是一个语句,其计算结果为布尔值,并带有可选消息:

You may find assertions are more what you need. An assertion is a statement which evaluates to a boolean result, with an optional message:

 assert (sky.state != FALLING) : "The sky is falling!";

每当断言结果为false时,断言失败,抛出包含您的消息的AssertionError是未检查的异常,意在退出应用程序)。

Whenever the assertion results in a false, the assertion fails and an AssertionError is thrown containing your message (this is an unchecked exception, intended to exit the application).

一个简单的事情是,这些被JVM处理为特殊的,并且可以在运行时切换到类级别,使用VM参数(无需重新编译)。如果未启用,则为零开销。

The neat thing is, these are treated special by the JVM and can toggled at runtime down to the class level, using a VM parameter (no recompile needed). If not enabled, there is zero overhead.

这篇关于如何从Java中的生产代码中删除调试语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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