技术开发 频道

使用Perf4J进行性能分析和监控

  下面的例子展现了如何轻松利用这些功能。可以通过Perf4J开发人员指南来了解集成Perf4J的详细信息。

  利用StopWatch类开发计时代码

  org.perf4j.LoggingStopWatch类用于在代码中添加计时语句并打印到标准输出或者日志文件中:  

StopWatch stopWatch = new LoggingStopWatch();

  
//... execute code here to be timed

  stopWatch.stop(
"example1", "custom message text");

  对stop()方法的调用记录了执行时间并打印日志信息。默认情况下,基类LoggingStopWatch将输出打印到System.err流中。但是大多数情况下,你需要使用一个集成到现有Java日志框架(如Log4JStopWatch、CommonsLogStopWatch或者Slf4JStopWatch)的子类。下面是一些stop watch的输出示例:  

start[1233364397765] time[499] tag[example1] message[custom message text]

  start[
1233364398264] time[556] tag[example1] message[custom message text]

  start[
1233364398820] time[698] tag[example1] message[custom message text]

  使用LogParser创建统计数据和图表

  虽然默认的stop watch输出相比直接调用System.currentTimeMillis()来说没有很大的改进,但真正的好处在于能够解析这些输出以生成统计数据和图表。LogParser通过tag和时间片把stop watch输出分组,生成详细的统计信息和可选的时间序列图(使用Google Chart API)。下面是一些使用默认文本格式(也支持csv格式)的示例输出:  

Performance Statistics 20:32:00 - 20:32:30

  Tag Avg(ms) Min Max Std Dev Count

  codeBlock1
249.4 2 487 151.3 37

  codeBlock2.failure
782.9 612 975 130.8 17

  codeBlock2.success
260.7 6 500 159.5 20

  Performance Statistics
20:32:30 - 20:33:00

  Tag Avg(ms) Min Max Std Dev Count

  codeBlock1
244.0 7 494 150.6 41

  codeBlock2.failure
747.9 531 943 125.3 21

  codeBlock2.success
224.1 26 398 106.8 21

  Performance Statistics
20:33:00 - 20:33:30

  Tag Avg(ms) Min Max Std Dev Count

  codeBlock1
289.3 10 464 141.1 22

  codeBlock2.failure
781.1 599 947 135.1 8

  codeBlock2.success
316.2 115 490 112.6 13

  平均执行时间和每秒事务处理量的图表以指向Google Chart Server的URL的形式生成。  

  同时,虽然LogParser默认从标准输入中读取数据,但是你也可以指定一个来自运行时服务器的日志文件,用LogParser实时输出:

  tail -f performance.log | java -jar perf4j-0.9.8.1.jar
0
相关文章