Pages

Debugging Application Performance With Perf4j

Performance is one of the main aspect that we all need to consider when implementing systems. Today's world of Service Oriented Architectures and distributed applications, detecting performance bottleneck is really a difficult task.

If someone asked "Why is my web app slow ?"  this requires investigation multiple components and execution paths, and it requires detailed performance data from all of the application components.

In order to get the performance data one of the most common practice is to get the execution time for given path. System.currentTime() is one approach to do this. But we need to have some custom mechanism to aggregate these results to analyze further.

Perf4j is an open source performance logging framework that specially design to solve the above scenario. Its a,

  • Simple stop watch mechanism to time statements.
  • Command line tool to generate aggregate statistics 
  • Can integrate with log4j
  • Provides @Profile annotation to use it with Aspects.
You can find more details explanation in here and here.

But here I will drive through with some detailed example to understand,
  • How to integrate perf4j with log4j
  • How to configure log4j.xml to use separate log file for performance results
  • Commands to aggregate performance log data
As usual you can find the sample code here.

First we will create a sample maven project and then create a class called PerformanceMonitor to hold the stop watch.
Add per4j and log4j dependencies to pom.xml
 <dependencies>  
     <dependency>  
       <groupId>org.perf4j</groupId>  
       <artifactId>perf4j</artifactId>  
       <version>${perf4j.version}</version>  
     </dependency>  
     <!-- Logging -->  
     <dependency>  
       <groupId>org.slf4j</groupId>  
       <artifactId>slf4j-api</artifactId>  
       <version>${slf4j.version}</version>  
     </dependency>  
     <dependency>  
       <groupId>org.slf4j</groupId>  
       <artifactId>slf4j-log4j12</artifactId>  
       <version>${slf4j.version}</version>  
     </dependency>  
   </dependencies>  


PerformanceMonitor.java
 public class PerformanceMonitor {  
   private static final ThreadLocal<StopWatch> WATCH = new ThreadLocal<StopWatch>() {  
     @Override  
     protected StopWatch initialValue() {  
       return new Log4JStopWatch(Logger.getLogger("instrument.org.perf4j.TimingLogger"));  
     }  
   };  
   public static void start(String tag) {  
     WATCH.get().start(tag);  
   }  
   public static void stop(String tag) {  
     WATCH.get().stop(tag);  
   }  
 }  

As you can clearly see I used this as a ThreadLocal instance because I'm expecting to run this application in multi-threaded environment.

Then configure log4j.xml
 <?xml version="1.0" encoding="UTF-8" ?>  
 <!DOCTYPE log4j:configuration SYSTEM  
     " http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">  
 <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">  
   <appender name="console" class="org.apache.log4j.ConsoleAppender">  
     <layout class="org.apache.log4j.PatternLayout">  
       <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %t %c{1}:%L - %m%n"/>  
     </layout>  
   </appender>  
   <appender name="trace" class="org.apache.log4j.DailyRollingFileAppender">  
     <param name="File" value="trace.log"/>  
     <param name="Threshold" value="debug"/>  
     <param name="DatePattern" value="'.'yyyy-MM-dd"/>  
     <layout class="org.apache.log4j.PatternLayout">  
       <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %t %c{1}:%L - %m%n"/>  
     </layout>  
   </appender>  
   <appender name="error" class="org.apache.log4j.DailyRollingFileAppender">  
     <param name="File" value="logs/vetstoria-oltp-error.log"/>  
     <param name="Threshold" value="error"/>  
     <param name="DatePattern" value="'.'yyyy-MM-dd"/>  
     <layout class="org.apache.log4j.PatternLayout">  
       <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %t %c{1}:%L - %m%n"/>  
     </layout>  
   </appender>  
   <appender name="statistics" class="org.apache.log4j.FileAppender">  
     <param name="File" value="perf.log"/>  
     <param name="Append" value="false"/>  
     <layout class="org.apache.log4j.PatternLayout">  
       <param name="ConversionPattern" value="%m%n"/>  
     </layout>  
   </appender>  
   <logger name="org.perf4j.TimingLogger">  
     <level value="info"/>  
     <appender-ref ref="statistics"/>  
   </logger>  
   <logger name="com.rd">  
     <level value="debug"/>  
     <appender-ref ref="console"/>  
     <appender-ref ref="trace"/>  
     <appender-ref ref="error"/>  
   </logger>  
   <logger name="instrument">  
     <level value="info"/>  
     <appender-ref ref="console"/>  
     <appender-ref ref="statistics"/>  
   </logger>  
 </log4j:configuration>  

Check the "org.per4j.TimingLogger" and "instrument" loggers carefully.  You can see the relevant appender called "statistics"  that will redirect output to a file called perf.log

App.java is pretty straightforward.

 public class App {  
   private static final Logger LOGGER = Logger.getLogger(App.class);  
   public static void main(String[] args) throws InterruptedException {  
     LOGGER.info("Starting .....");  
     PerformanceMonitor.start("METHOD1");  
     method1();  
     PerformanceMonitor.stop("METHOD1");  
     PerformanceMonitor.start("METHOD2");  
     method2();  
     PerformanceMonitor.stop("METHOD2");  
     LOGGER.info("Completed. Please check the perf.log file for time logging");  
   }  
   private static void method1() throws InterruptedException {  
     Thread.sleep(5000);  
   }  
   private static void method2() throws InterruptedException {  
     Thread.sleep(2000);  
   }  
 }  


Then run the App.java main method and this will create two log files in same hierarchy. All the performance related logs populate into a file called perf.log.

When you inspect the perf.log file you can see the following output.
 start[1444722158471] time[5000] tag[METHOD1]  
 start[1444722163472] time[2000] tag[METHOD2]  

To get aggregate results,

  1. Download per4j jar. (http://mvnrepository.com/artifact/org.perf4j/perf4j/0.9.16)
  2. Run following command
 java -jar <perf4j.location>/perf4j-0.9.16.jar --timeslice 3000000000 --format csv perf.log -o output.csv  

Open up the output.csv and you can see the aggregated performance results.

70 comments:

  1. Really Good blog post.provided a helpful information about debugging application performance.keep updating...
    Digital marketing company in Chennai

    ReplyDelete
  2. https://edutry.blogspot.in/2017/05/augmented-reality-for-products.html?showComment=1510748334817#c8070672859228630519

    ReplyDelete
  3. Hi dear, I like your post so much, and it is very good. Hope that we can communicate with each other. I want to introduce an aso services, I try it and I feel it is so good to us beginners.

    ReplyDelete
  4. This is an incredible rousing article.I am essentially satisfied with your great work.You put truly exceptionally accommodating data. Keep it up. Continue blogging. Hoping to perusing your next post.
    Brother And Sister Quotes
    Happy Birthday SMS

    ReplyDelete
  5. the difference format external hard drive windows 10 in price could be tangible damages. Your data is your data and it is characterized by this size. Unless you are planning on deleting large chunks of data, shrinking is not going to do much of anything.

    ReplyDelete
  6. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
    Aws Training in Chennai
    Advanced Aws Training in Chennai

    ReplyDelete
  7. Maxatron Plus do you want to be subjected to constant doctor visits and tests, take painful testosterone injections or would you rather use a natural enhancement pill to boost your testosterone levels?

    ReplyDelete
  8. Bionatrol Pro Enhance really expensive as well as inconvenient in some point because you have to wear these devices for about two to six hours everyday. This can be difficult for most men especially those who have active lifestyle.

    ReplyDelete
  9. Synergex 7 about their manhood, especially when they come to a point in their life when they feel they need to prove something. Most men want to enhance their male organ for sexual purposes:

    ReplyDelete
  10. Ryzex Male Enhancement hand involves your health, so it is vital that careful understanding and study of each of the options available be made before settling on one solution or a combination of many.

    ReplyDelete
  11. Keto Gedeon then eat 4-6 small meals during the day. The reason to this might be the fact that they get hungrier later on in the day, and might have a tendency to over eat during other meals of the day.

    ReplyDelete
  12. Super Fast Keto Boost Take joy in small progress. Acknowledge yourself when you have done little and consistent weight loss progresses. Do not be too harsh on

    ReplyDelete
  13. This blog is definitely entertaining additionally factual. I have picked up helluva helpful tips out of this amazing blog. I ad love to visit it again and again. Thanks!
    We are providing Background Removal Service with more than 15 years of experience.

    ReplyDelete
  14. So not only does a herbal Pro Keto Rx slimming patch level out your metabolism which means quicker and more efficient fat burning but also stop you from getting food cravings, so it acts as a dual action system, helping you lose weight faster.

    ReplyDelete
  15. Studies that compare the psychological characteristics of people who have successfully kept the weight off to people who have regained the weight, see clear differences between these two groups. For example, one study that looked at 28 obese women who had lost weight but


    Number One Keto

    ReplyDelete
  16. Weight problems are Keto Shred Biotic Immunity Booster the results of a condition of an individual's body exceeding the very least of 10% of the perfect body weight.

    ReplyDelete
  17. cardiovascular exercise that you can, following the completion of your body training exercises. Start yourself at ten minutes and work your way up to thirty minutes. This is the preparation step necessary for a successful Phase II of your healthy weight loss and quick weight loss.
    Keto Shred Biotic Immunity Booster

    ReplyDelete
  18. it will be and you'll be Keto Shred Biotic Immunity Booster more successful. The most important tool is knowledge. If you want to burn fat fast you will need to know how to do it properly so that you can achieve not only quick, but also long lasting results.

    ReplyDelete
  19. However with this type of PuriGlow Cream face lift treatment you should know that you will not get overnight result. Any product that promises overnight result is misleading.

    ReplyDelete
  20. The rest of the world is Fresh Prime Keto keeping pace pound for pound. As a species, we are getting steadily fatter, day by day, year by year. This is not just a question of vanity.

    ReplyDelete
  21. your belly fat. Once Xtreme Keto Boost I reached that plateau in my weight loss journey, nothing I did seemed to matter until I discovered these 5 fat burning foods.

    ReplyDelete
  22. which stores excess caloric Electro Keto energy for use in times of famine. Unfortunately our genetically programmed survival mechanism leads to failure for the majority of people trying to lose weight.

    ReplyDelete
  23. Well known for its nature of Cylophin RX increasing sexual performance even if the consumer has erectile dysfunction. This power herb can give you awesome result that you can have several orgasms within the night.

    ReplyDelete
  24. You may have never dreamed Fresh Prime Keto that there are fat burning foods which could cause natural weight loss and keep you from needing to spend hours in the gym trying to get rid of your belly fat. Once I reached that plateau in my weight loss journey, nothing I did seemed to matter until I discovered these 5 fat burning foods.

    ReplyDelete
  25. fulfilling her needs, it never hurts to do increase your penis size... well, at least it won't if you know the proper way of doing so.
    Empowered x Energy

    ReplyDelete
  26. By increasing androgenic effects Formax Lean Male Enhancement and Formax Lean Male Enhancement dramatically increasing testosterone, Tongkat Ali increases sexual arousal and motivation and frequency of sexual activity.

    ReplyDelete
  27. You may have never dreamed that there Reliant Keto are fat burning foods which could cause natural weight loss and keep you from needing to spend hours in the gym trying to get rid of your belly fat. Once I reached that plateau in my weight loss journey, nothing I did seemed to matter until I discovered these 5 fat burning foods.

    ReplyDelete
  28. These include such ingredients such as turkey, Reliant Keto quality carbohydrates, tuna, fruits and oatmeal to name a few. Proteins like the onces mentioned above and carbohydrates should be eaten together in every meal and they should be in the right balance to lose weight.

    ReplyDelete
  29. more calories then you consume the well accepted Befit Keto Cut will cause you to lose weight. To some degree, they all work: Atkins-style, no carb diets, low fat high carb diets, all manner of fad diets - it simply does not matter in the short term.

    ReplyDelete
  30. Here in this article we are going Viadine Male Enhancement to go over a few of my favourite natural male enhancement tips. However, before I get into it, it's probably quite important for you to recognise that being the writer of literally hundreds and hundreds of male enhancement articles and blog posts.

    ReplyDelete
  31. Now, you don't need to Bio Jolt Male Enhancement gulp down a gallon of OJ every day as it does have tons of sugars in it, but do a little analysis and take a look at the many fruits on the market which are rich in Vitamin C which will help bring about natural.

    ReplyDelete
  32. The solutions for weight loss before might Keto Now Real not be so effective with today's lifestyle. If you're overweight, there's not doubt you'd like to start losing belly fat. Here are some basic guidelines to help you get started.

    ReplyDelete
  33. Few Javelin Male Enhancement people would disagree that men and women are different in many ways, and their diet is no exception. While both sexes should avoid health degrading foods such as trans fat rich baked and fried items along with sugar and fructose laden soft drinks and desserts, there are certain foods which are especially important to male health.

    ReplyDelete
  34. Mood is deeply affected by a combination of factors including neurotransmitter function in the brain, environmental Sildaxin and life changes and the diet we eat. Diet is the factor which is directly within our control, and the foods we eat can play a big role in the way we perceive others and the world around us.Men are best served eating plenty of fiber rich carbohydrates from fresh vegetable, and to a much lesser extent, fruits and grains. These foods hold blood sugar swings in check which help maintain proper brain chemistry balance.

    ReplyDelete
  35. Gastric Bypass Roux-en-Y is a recently developed procedure Nutrifix Keto that utilizes the principles of both restrictive and malabsorptive weight loss surgeries. According to the American Society for Bariatric Surgery and the National Institutes of Health, Roux-en-Y gastric bypass is the most frequently performed weight loss surgery in the United States.

    ReplyDelete
  36. product time and time again on the television or radio does not Supersonic Keto mean it will be effective in losing permanent weight. All these weight loss companies are trying to do is get their product in front of you over and over so it will be there when you're ready to buy. Many people make the mistake of assuming a product is credible simply because it's constantly on television.

    ReplyDelete
  37. ones that delight me. In The Myth of Male Power I documented the seven-to-one discrimination against funding for prostate VitaBiogen versus breast cancer research, and stressed this on the flap jacket and in interviews. I am delighted

    ReplyDelete
  38. Yes, it is the diet that allows you to continue eating pretty much the same as you did before although there Fresh Prime Keto is some emphasis on daily exercise

    ReplyDelete
  39. was because Vigrafirmt Male Enhancement of the potent ingredient Cialis was involved. It helps promote a large increase in blood flow throughout the body

    ReplyDelete
  40. It is illogical to think that your health and weight are going to be in balance if your nutrition consists mainly Nutrapharmex Keto of twinkies, chips, and donuts. Sure you can burn it off by exercising, but most people whose diet consists of mainly junk food are probably not disciplined enough to stick to a workout routine. I do know a few people who, from the outside, look like they are in good shape, because they are not "fat, but who have high cholesterol.

    ReplyDelete
  41. With a gentleman Biolife Keto from England who was considering this whole issue of legalizing drugs, and if that was the solution to take the money from the Drug Cartels, raise tax revenues,

    ReplyDelete
  42. director of the Rocky Fresh Prime Keto Mountain High Intensity Drug Trafficking Area program, to find out how bad the heroin problem has become in Denver.

    ReplyDelete
  43. abused drugs in Eclipse Keto Denver remain alcohol and marijuana. However, heroin's climb in popularity does not seem to be declining. In 2010 heroin overdoses

    ReplyDelete
  44. and the drugs are Ciagenix becoming more potent, more toxic, and causing greater health risks than ever before. If people are allowed to do drugs, I don't want my tax dollars subsidizing new heart valves at age 35.

    ReplyDelete
  45. So when you Best Boots for Hiking are looking to purchase Timberland Boots you just have to go online and from the comfort of your home or office and start shopping.

    ReplyDelete
  46. and ways of viewing Biolife Keto a diet program that will allow you to decide, once and for all, if it's the right diet for you. You may not always like what I have to say

    ReplyDelete
  47. That resulted in this product getting pulled from the shelves is called Tadalafil, or more commonly known VitaBiogen as Cialis. This ingredient is common in some prescription based male enhancement products.

    ReplyDelete
  48. Abused drugs in Keto Plus Pro Denver remain alcohol and marijuana. However, heroin's climb in popularity does not seem to be declining. In 2010 heroin overdoses ranked third behind marijuana and cocaine for emergency room visits

    ReplyDelete
  49. And ways of Oxyphen Keto XR viewing a diet program that will allow you to decide, once and for all, if it's the right diet for you

    ReplyDelete
  50. Statistics from Keto Super Powder drug rehabs in Colorado also reflect heroin's popularity.. Marc Condoljani, associate director of community intervention programs at the Colorado division of behavioral health said.

    ReplyDelete
  51. Bused drugs Prime TRT in Denver remain alcohol and marijuana. However, heroin's climb in popularity does not seem to be declining.

    ReplyDelete
  52. Statistics from Alpha Evolution Keto drug rehabs in Colorado also reflect heroin's popularity.. Marc Condoljani, associate director of community intervention programs at the Colorado division of behavioral health said

    ReplyDelete
  53. That resulted Oxyphen Keto XR in this product getting pulled from the shelves is called Tadalafil, or more commonly known as Cialis. This ingredient is common in some prescription based male enhancement products.

    ReplyDelete
  54. Married women Novum Keto Reviews preferred Bush; unmarried women overwhelmingly preferred Gore. Why? Voting motivations are complex, but Gore promised more government protection, and unmarried women often seek the government as substitute husband-or substitute protector.

    ReplyDelete
  55. in natural Erecerxyn formulas in products that are advertised to be safe. Male Power Plus isn't the first product to be recalled because of complications from a dangerous drug that is in their formula, and will not be the last. This is why it is so important to consumers that a product they want to purchase has clinical trials done on it and has a plethora of information available about the product itself.

    ReplyDelete
  56. diet that works most of the time must seem as complicated as nuclear physics. It's not, but there are Eternal Nutrition Keto a bewildering number of choices for diets out there. High fat or no fat? High carbohydrate or no carbohydrate? Low protein or high protein? To make matters worse, there are a million variations and combinations to the above diet scenarios to add to the confusion. It seems endless and causes many people to throw up their hands in frustration and give up. In this article I will attempt to change all that.

    ReplyDelete
  57. Heroin Male Max 100 hasn't reached the level of other drugs yet, but pharmaceutical opiate abuse is skyrocketing. Those drugs are more expensive than heroin, and that moves people to go from opiates to heroin.

    ReplyDelete
  58. workout routine Warrior Keto is great, there are a few things you should consider: the first being that everyone is at a different level when it comes to their fitness and how much intensity they can actually handle

    ReplyDelete
  59. The information given in this article is very good and I like it. I have also written this kind of blog you can also read for more knowledge.
    why cloud computing is needed
    benefits of machine learning
    benefits of devops
    php vs .net
    js interview questions
    ethical hacking interview questions

    ReplyDelete
  60. Workout routine is great, there are a few things you should consider: the first being that everyone is Keto Dual System at a different level when it comes to their fitness and how much intensity they can actually handle. If you have been physically inactive for a number of years, an intense work out for you might be, walking half a mile a day

    ReplyDelete
  61. Is a trend that has drug rehabs concerned. Recently, pain pill manufacturers have made it more difficult to abuse Acidaburn prescription drugs by making more time released capsules with special coatings that are hard to abuse. Also, many pain management clinics across the United States are being forced to shut their doors. These closings have driven up the street price of prescription pain pills

    ReplyDelete
  62. This is really a good article. Thanks for taking the time to provide us some useful and exclusive information. Keep sharing new blogs.
    ios technology
    hadoop tools
    benefits of cloud computing
    types of cloud computing
    networking interview questions and answers
    nodejs interview questions

    ReplyDelete
  63. Was because of the potent ingredient Cialis was involved. It helps promote a large increase in blood flow Biocore Muscle throughout the body. This is the best method to use when it comes to curing erectile dysfunction. The problem with using this ingredient is that it can cause large decreases in blood pressure that can be very dangerous for men of any age. Most natural formulas utilize natural aphrodisiacs like Yohimbe and Epimedium because they do not come with adverse side effects and can be very potent on their own

    ReplyDelete
  64. ones that Keto Wave delight me. In The Myth of Male Power I documented the seven-to-one discrimination against funding for prostate versus breast cancer research, and stressed this on the flap jacket and in interviews. I am delighted to see the funding for both cancers has increased and the gap has decreased.

    ReplyDelete
  65. in natural Ezslimfit Complete Keto formulas in products that are advertised to be safe. Male Power Plus isn't the first product to be recalled because of complications from a dangerous drug that is in their formula, and will not be the last.

    ReplyDelete
  66. So when you Ketovita Reviews are looking to purchase Timberland Boots you just have to go online and from the comfort of your home or office and start shopping

    ReplyDelete
  67. Your site is good Actually. Thanks for sharing this information. I really like your way of expressing the opinions and sharing the information. It is good to move as chance bring new things in life, paves the way for advancement, etc. But it is well known to everyone that moving to new location with bulk of goods is not an easy task to move or shift from one place to other place because I have experienced about that and I face the problem like that. There I go to village near to my city faced that problem there. Allfreedumps//AWS-Certified-Solutions-Architect-Professional//350-601

    ReplyDelete