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

查看:230
本文介绍了如何从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天全站免登陆