使用java.util.logging的好例子 [英] Good examples using 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.
一般情况下,位于每个班级的顶部,您应该:
In general, at the top of every class, you should have:
private static final Logger LOGGER = Logger.getLogger( ClassName.class.getName() );
然后,您可以使用Logger 类。
对于执行流程顶级调试的任何内容,请使用 Level.FINE
:
Use Level.FINE
for anything that is debugging at the top level of execution flow:
LOGGER.log( Level.FINE, "processing {0} entries in loop", list.size() );
使用 Level.FINER
/ Level.FINEST
循环内部以及在调试基本流问题时可能并不总是需要看到那么多细节的地方:
Use Level.FINER
/ Level.FINEST
inside of loops and in places where you may not always need to see that much detail when debugging basic flow issues:
LOGGER.log( Level.FINER, "processing[{0}]: {1}", new Object[]{ i, list.get(i) } );
使用参数化版本的日志工具来防止产生大量的GC串联垃圾跟上。 对象[]
如上所述,通常在堆栈分配上很便宜。
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
为异常
时日志文件,我也可以看到消息。否则,它将出现在堆栈转储生成的下一行输出中,并且您必须使用更高级的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屋!