2

I'm writing an app that is working with db via org.springframework.jdbc.core.JdbcTemplate. I need to log execution of those queries. So I have methods that have some jdbctemplate logic, for example

List<Map<String, Object>> data = jdbcTemplate.queryForList(queryTables);

I need to log time of execution of this query but not of the all method. I can do that via milliseconds subtraction. But it is not the case if I have 1500 methods or even more. So is there any annotation or any other method that can help me to log execution time?

  • Where does JdbcTemplate have its origin? Using Aspects might be an option but this creates overhead which must at least be kept in mind. – Markus Jun 20 '17 at 14:50
  • In short no. You can use what @Markus suggests or look into the DB itself. It may allow you to that programmatically – bichito Jun 20 '17 at 14:52
  • Im not sure whats the best way to calculate the time but I made an example code where Im calculating the execution time of multiples methods. Hope it works: https://stackoverflow.com/questions/27112162/why-is-multiplied-many-times-faster-than-taking-the-square-root – xsami Jun 20 '17 at 15:28
  • Oh and some databases allow query logging. This would have the advantage to factor out network and stuff from the measurement. – Markus Jun 20 '17 at 20:46
  • my application needs to work with any db so that is not the solution – Bohdan Levkovych Jun 21 '17 at 08:48

1 Answers1

2
  1. spring use StopWatch for mesure execution time , also apache has the same StopWatch . example for stopwatch - https://www.javacodegeeks.com/2012/08/measure-execution-time-in-java-spring.html

  2. use aop for execution time . here are example https://veerasundar.com/blog/2010/01/spring-aop-example-profiling-method-execution-time-tutorial/

    with aop and custom annotation you can mark method that you want to log execution time.

aop - it's not so big overhead , when you use @Transactional you also use aop , so you already have this overhad


if you want to log execution time only for dbcTemplate.queryForList() and in couple plase , use stopwatch. or you can create your own util method (wrap dbcTemplate.queryForList()) , something like :

public static List<?> queryForListWithLogExecution(String sql){
     List<?> result;
     //measuring elapsed time using Spring StopWatch
        StopWatch watch = new StopWatch();
        watch.start();
        list = jdbcTemplate.queryForList(queryTables); 
        watch.stop();
        logger.info("Total execution time in millis: {0}", watch.getTotalTimeMillis());
        return result;
}
Community
  • 1
  • 1
xyz
  • 5,228
  • 2
  • 26
  • 35