使用 java.util.logging 的好例子 [英] Good examples using java.util.logging

查看:28
本文介绍了使用 java.util.logging 的好例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的程序中使用日志.我听说过 java.util.logging,但我不知道如何开始.

I want to use logs in my program. I heard about java.util.logging, but I don't know how to begin.

有什么例子可以说明我可以用日志做什么?我将如何在自己的程序中使用登录?

Are there any examples of what can I do with logging? How would I use logging in my own program?

推荐答案

java.util.logging 使您不必再随身携带一个 jar 文件与您的应用程序一起使用,并且它与一个好的格式化程序一起工作得很好.

java.util.logging keeps you from having to tote one more jar file around with your application, and it works well with a good Formatter.

一般来说,在每个班级的顶部,您应该:

private static final Logger LOGGER = Logger.getLogger( ClassName.class.getName() );

然后,您可以使用 Logger 类.

Then, you can just use various facilities of the Logger class.

Level.FINE 用于在执行流程的顶层进行调试的任何内容:

LOGGER.log( Level.FINE, "processing {0} entries in loop", list.size() );

<小时>

在循环内部以及在调试基本流程问题时您可能并不总是需要查看那么多细节的地方使用 Level.FINER/Level.FINEST:>

LOGGER.log( Level.FINER, "processing[{0}]: {1}", new Object[]{ i, list.get(i) } );

使用日志工具的参数化版本来避免生成大量 GC 必须跟上的字符串连接垃圾.上面的 Object[] 很便宜,通常在堆栈分配上.

Use the parameterized versions of the logging facilities to keep from generating tons of String concatenation garbage that GC will have to keep up with. Object[] as above is cheap, on the stack allocation usually.

通过异常处理,始终记录完整的异常详细信息:

With exception handling, always log the complete exception details:

try {
    ...something that can throw an ignorable exception
} catch( Exception ex ) {
    LOGGER.log( Level.SEVERE, ex.toString(), ex );
}

我总是在这里传递 ex.toString() 作为消息,因为当我grep -n"为Exception"时在日志文件中,我也可以看到该消息.否则,它将出现在堆栈转储生成的下一行输出中,并且您还必须有一个更高级的 RegEx 来匹配该行,这通常会为您提供比您需要查看的更多的输出.

I always pass ex.toString() as the message here, because then when I "grep -n" for "Exception" in log files, I can see the message too. Otherwise, it is going to be on the next line of output generated by the stack dump, and you have to have a more advanced RegEx to match that line too, which often gets you more output than you need to look through.

这篇关于使用 java.util.logging 的好例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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