Log time in java

Apache Log4j Logging with specific timezone

I want the log should contain date entries of specific timezone. Is there any way of forcing timezone in log4j.properties ? Now I am using JDK 1.5, As you already know that there is timezone bug in JDK 1.5 that is removed in JDK 1.5. In case of JDK 1.5 it by default shows «GMT» timezone. I want to configure in Log4j my specific timezone.

6 Answers 6

This will allow you to see timezone information in each line of your logs:

The trick is to include ‘zzz’ in the pattern since according to Javadoc for java.text.SimpleDateFormat ( http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html ), that’s the code for timezone. Log4J uses the same rules as SimpleDateFormat.

There are more details over the in the Log4J Javadoc:

Look for the row in the table where the ‘Conversion Character’ is the letter ‘d’.

Oh. Sorry. In that case here’s your solution (needs an «extras» jar): stackoverflow.com/questions/1785725/…

Quoting important part of the PatternLayout ‘s javadoc: Although part of the standard JDK, the performance of SimpleDateFormat is quite poor. For better results it is recommended to use the log4j date formatters. These can be specified using one of the strings «ABSOLUTE», «DATE» and «ISO8601» for specifying AbsoluteTimeDateFormat, DateTimeDateFormat and respectively ISO8601DateFormat. For example, %d or %d.

Читайте также:  Численное вычисление интеграла python

Yeah, but by «quite poor» they mean it can do 10,000 formats per second. Frankly, if this represents a major performance bottleneck of your app, then you deserve a glass of champagne.

The best way is to use the Apache Extras™ for Apache log4j™ And replace The normal PatternLayout by org.apache.log4j.EnhancedPatternLayout doing the following if using a property file:

//log4j.appender.xxx.layout = org.apache.log4j.PatternLayout //Replaced by log4j.appender.xxx.layout = org.apache.log4j.EnhancedPatternLayout 

Then you can use %d instead of %d in the ConversionPattern to display your date in the GMT format. Any timezone can be specified instead of GMT

There are three steps to this:

1) Add the log4j-extras dependency here

2) Set the layout to EnhancedPatternLayout: log4j.appender.stdout.layout=org.apache.log4j.EnhancedPatternLayout (change stdout to whatever appender you are using)

3) Add your timezone in braces after your date time pattern log4j.appender.stdout.layout.ConversionPattern=%d %-5p %c:%L — %m%n (Here IST in my case)

You can refer to list of timezone ID’s available in java here or here

Use the org.apache.log4j.helpers.DateLayout as the layout class and the property timeZone in it.

Include a date argument in your ConversionPattern . From the PatternLayout documentation:

Used to output the date of the logging event in the local time zone. To output the date in universal time use the %utcdate pattern. The date conversion specifier may be followed by a date format specifier enclosed between braces. For example, %date or %date . If no date format specifier is given then ISO8601 format is assumed ( Iso8601DateFormatter ).

The date format specifier admits the same syntax as the time pattern string of the ToString .

For better results it is recommended to use the log4net date formatters. These can be specified using one of the strings «ABSOLUTE», «DATE» and «ISO8601» for specifying AbsoluteTimeDateFormatter , DateTimeDateFormatter and respectively Iso8601DateFormatter . For example, %date or %date .

These dedicated date formatters perform significantly better than ToString .

Источник

Java start and end time logging in java

A simple solution to get basic monitoring functionality for the execution time of our methods, we can make use of the PerformanceMonitorInterceptor class out of Spring AOP (Aspect Oriented Programming). In this tutorial, we’ll look into a couple of basic options the Spring Framework offers for performance monitoring.

How would you break down and log the execution times of different parts of your application?

Please have a look at SLF4J profiler. Interestingly enough. tt was developed to answer the exact same need, that is to measure and improve the performance of SOAP calls.

Sounds like a job for Perf4J.

  1. create a PerformanceTimer class, which exposes:
    • recordWaitedForWebServerReponse(operationId, time);
    • recordMassagedData(operationId, time);
    • other methods, if needed
  2. inject that class where it’s needed;
  3. have the PerformanceTimer maintain a concurrent map of OperationId -> OperationTimingData;
  4. on the method call known to be the last, invoke Log4j with the output you desired.

Start and end time logging in Java Code Example, long startTime = System.nanoTime(); methodToTime(); long endTime = System.nanoTime(); long duration = (endTime — startTime);

Spring AOP — Custom annotation to log method execution Time

This video explain you How to Create Custom annotation to log method execution time using Duration: 14:39

Spring Performance Logging

1. Overview

In this tutorial, we’ll look into a couple of basic options the Spring Framework offers for performance monitoring.

2. PerformanceMonitorInterceptor

A simple solution to get basic monitoring functionality for the execution time of our methods, we can make use of the PerformanceMonitorInterceptor class out of Spring AOP (Aspect Oriented Programming).

Spring AOP allows the defining of cross-cutting concerns in applications, meaning code that intercepts the execution of one or more methods, in order to add extra functionality.

The PerformanceMonitorInterceptor class is an interceptor that can be associated with any custom method to be executed at the same time. This class uses a StopWatch instance to determine the beginning and ending time of the method run.

Let’s create a simple Person class and a PersonService class with two methods that we will monitor:

public class PersonService < public String getFullName(Person person)< return person.getLastName()+" "+person.getFirstName(); >public int getAge(Person person) < Period p = Period.between(person.getDateOfBirth(), LocalDate.now()); return p.getYears(); >>

In order to make use of the Spring monitoring interceptor, we need to define a pointcut and advisor:

@Configuration @EnableAspectJAutoProxy @Aspect public class AopConfiguration < @Pointcut( "execution(public String com.baeldung.performancemonitor.PersonService.getFullName(..))" ) public void monitor() < >@Bean public PerformanceMonitorInterceptor performanceMonitorInterceptor() < return new PerformanceMonitorInterceptor(true); >@Bean public Advisor performanceMonitorAdvisor() < AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); pointcut.setExpression("com.baeldung.performancemonitor.AopConfiguration.monitor()"); return new DefaultPointcutAdvisor(pointcut, performanceMonitorInterceptor()); >@Bean public Person person() < return new Person("John","Smith", LocalDate.of(1980, Month.JANUARY, 12)); >@Bean public PersonService personService() < return new PersonService(); >>

The pointcut contains an expression that identifies the methods that we want to be intercepted — in our case the getFullName() method of the PersonService class.

After configuring the performanceMonitorInterceptor() bean, we need to associate the interceptor with the pointcut. This is achieved through an advisor, as shown in the example above.

Finally, the @EnableAspectJAutoProxy annotation enables AspectJ support for our beans. Simply put, AspectJ is a library created to make the use of Spring AOP easier through convenient annotations like @Pointcut .

After creating the configuration, we need to set the log level of the interceptor class to TRACE , as this is the level at which it logs messages.

For example, using Jog4j, we can achieve this through the log4j.properties file:

log4j.logger.org.springframework.aop.interceptor.PerformanceMonitorInterceptor=TRACE, stdout

For every execution of the getAge() method, we will see the TRACE message in the console log:

2017-01-08 19:19:25 TRACE PersonService:66 - StopWatch 'com.baeldung.performancemonitor.PersonService.getFullName': running time (millis) = 10

3. Custom Performance Monitoring Interceptor

If we want more control over the way the performance monitoring is done, we can implement our own custom interceptor.

For this, let’s extend the AbstractMonitoringInterceptor class and override the invokeUnderTrace() method to log the start, end, and duration of a method, as well as a warning if the method execution lasts more than 10 ms:

public class MyPerformanceMonitorInterceptor extends AbstractMonitoringInterceptor < public MyPerformanceMonitorInterceptor() < >public MyPerformanceMonitorInterceptor(boolean useDynamicLogger) < setUseDynamicLogger(useDynamicLogger); >@Override protected Object invokeUnderTrace(MethodInvocation invocation, Log log) throws Throwable < String name = createInvocationTraceName(invocation); long start = System.currentTimeMillis(); log.info("Method " + name + " execution started at:" + new Date()); try < return invocation.proceed(); >finally < long end = System.currentTimeMillis(); long time = end - start; log.info("Method "+name+" execution lasted:"+time+" ms"); log.info("Method "+name+" execution ended at:"+new Date()); if (time >10) < log.warn("Method execution longer than 10 ms!"); >> > >

The same steps for associating the custom interceptor to one or more methods as in the preceding section need to be followed.

Let’s define a pointcut for the getAge() method of PersonService and associate it to the interceptor we have created:

@Pointcut("execution(public int com.baeldung.performancemonitor.PersonService.getAge(..))") public void myMonitor() < >@Bean public MyPerformanceMonitorInterceptor myPerformanceMonitorInterceptor() < return new MyPerformanceMonitorInterceptor(true); >@Bean public Advisor myPerformanceMonitorAdvisor()

Let’s sets the log level to INFO for the custom interceptor:

log4j.logger.com.baeldung.performancemonitor.MyPerformanceMonitorInterceptor=INFO, stdout

The execution of the g etAge() method produced the following output:

2017-01-08 19:19:25 INFO PersonService:26 - Method com.baeldung.performancemonitor.PersonService.getAge execution started at:Sun Jan 08 19:19:25 EET 2017 2017-01-08 19:19:25 INFO PersonService:33 - Method com.baeldung.performancemonitor.PersonService.getAge execution lasted:50 ms 2017-01-08 19:19:25 INFO PersonService:34 - Method com.baeldung.performancemonitor.PersonService.getAge execution ended at:Sun Jan 08 19:19:25 EET 2017 2017-01-08 19:19:25 WARN PersonService:37 - Method execution longer than 10 ms!

4. Conclusion

In this quick tutorial, we’ve introduced simple performance monitoring in Spring.

As always, the full source code for this article can be found over on Github.

Java/Logging: How to log to separate log file every time?

It’s possible to do this entirely through configuration. There’s an example in the logback documentation:

How to log time taken by Rest web service in Spring Boot?, 5 Answers 5 · have you logged start time here? – VeKe · @SeeKing It only log the total time in ms, but if you want to know the start time and end

Источник

How to use Spring Framework StopWatch() to Log ExecutionTime and ElapseTime of any Java Thread

Spring Framework - StopWatch Examples

Spring Framework – StopWatch() is a very handy utility for any Java developer if you have small Java application or production ready application. Most of the Java applications involve Thread pooling or multiple simultaneous job invocation at the same time.

Then you are at right place. In this tutorial we will go over steps on how to measure and report time taken by each and every thread or Java Methods.

Let’s get started:

StopWatch is a simple stop watch, allowing for timing of a number of tasks, exposing total running time and running time for each named task.

You need Spring MVC core Maven dependency to get this program run.

 org.springframework spring-core 5.0.3.RELEASE  

Please add above maven dependency to your Maven Project and follow below steps.

  • Create class CrunchifySpringFrameworkStopWatch.java
  • Create StopWatch object crunchifyWatch
  • Start and Stop crunchifyWatch object during performTask1() and performTask2() operation
  • Return totalTimesInSeconds
  • In addition to print complete StopWatch result in prettyPrint format
  • We are using all below operations on StopWatch to print different results.
    • getTotalTimeSeconds()
    • prettyPrint()
    • shortSummary()
    • getTaskCount()
    • getLastTaskInfo().getTaskName()

    Kindly take a look at code for more detailed description.

    CrunchifySpringFrameworkStopWatch.java

    package crunchify.com.tutorial; import org.springframework.util.StopWatch; /** * @author Crunchify.com Use StopWatch to expose total running time of any Java Threads */ public class CrunchifySpringFrameworkStopWatch < public static void main(String[] args) < // StopWatch is a simple stop watch, allowing for timing of a number of tasks, exposing total running time and running time for each // named task. StopWatch crunchifyWatch = new StopWatch("CrunchifyThreads"); CrunchifySpringFrameworkStopWatch crunchifyThread = new CrunchifySpringFrameworkStopWatch(); crunchifyWatch.start("CrunchifyThread-1"); crunchifyThread.performTask1(); crunchifyWatch.stop(); crunchifyWatch.start("CrunchifyThread-2"); crunchifyThread.performTask2(); crunchifyWatch.stop(); System.out.println("CrunchifyThreads took total: " + crunchifyWatch.getTotalTimeSeconds() + " seconds"); // prettyPrint() return a string with a table describing all tasks performed. For custom reporting, call getTaskInfo() and use the // task info directly. System.out.println("\n1. prettyPrint Result: " + crunchifyWatch.prettyPrint()); // Return a short description of the total running time. System.out.println("2. Short Summary: " + crunchifyWatch.shortSummary()); // Return the number of tasks timed. System.out.println("3. Total Task Count: " + crunchifyWatch.getTaskCount()); // Return the name of this task. System.out.println("4. Last Task Name: " + crunchifyWatch.getLastTaskInfo().getTaskName()); >private void performTask1() < Runnable myRunnable = new Runnable() < public void run() < System.out.println("Crunchify Task 1 running"); >>; Thread crunchifyThread = new Thread(myRunnable); crunchifyThread.start(); > private void performTask2() < System.out.println("Crunchify Task 2 running \n"); for (int i = 1; i catch (InterruptedException e) < e.printStackTrace(); >> System.out.println(""); > >

    Just run above program as a Java in your Eclipse environment or stand alone using Terminal or Windows DOS and you will see performTask2() method take 10 seconds as we have for loop with count 5 and 2 seconds Thread timeout.

    Eclipse console output:

    Crunchify Task 1 running Crunchify Task 2 running Running Loop # 1 Running Loop # 2 Running Loop # 3 Running Loop # 4 Running Loop # 5 CrunchifyThreads took total: 10.006Seconds 1. prettyPrint Result: StopWatch 'CrunchifyThreads': running time (millis) = 10006 ----------------------------------------- ms % Task name ----------------------------------------- 00001 000% CrunchifyThread-1 10005 100% CrunchifyThread-2 2. Short Summary: StopWatch 'CrunchifyThreads': running time (millis) = 10006 3. Total Task Count: 2 4. Last Task Name: CrunchifyThread-2

    Let me know what you think of StopWatch. I personally use SpringFramework’s StopWatch in all of my applications.

    If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion.

    Suggested Articles.

    Источник

Оцените статью