I am trying to find out the time taken for certain methods to execute in my Java web application. I have some log entries which uses log4j. Now, can I rely on the timestamps on the log entries to get an approximate time taken by each section of my code to execute? Currently, I don't have the flexibility to attach a profiler to my JVM.
Asked
Active
Viewed 2,873 times
0
-
I really don't get your question. Of course you can take your calculator and manually compute deltas based on timestamps of log entries. But we can't tell you if the resolution that you gain from such activities is good enough for you. You are the person who decides if those numbers are good enough for your use case. – GhostCat Jul 04 '16 at 11:47
-
http://stackoverflow.com/questions/358225/log4j-with-timestamp-per-log-entry, you can log, System.CurrentMilliseconds() where ever you want.. – peaceUser Jul 04 '16 at 11:48
-
To give a hint on the second part of your question: if you need such information, and you can't attach a profiler; then there is no other way than have your code write out a lot of timestamps. – GhostCat Jul 04 '16 at 11:54
-
I generally use guava stopwatch in scenarios such as yours and use log4j for logging it, but without a profiler you might end up with big logs – sash Jul 04 '16 at 12:04
-
@Jägermeister my concern here is if the logs in log4j are printed out from the same thread or will it use a different thread to write to the file. – Halley Jul 04 '16 at 12:23
-
That will properly depend on how you configure log4j; I guess by default, it happens on the same thread. – GhostCat Jul 04 '16 at 12:29
2 Answers
0
You can parse the dates of the log and keep it readable!.
Example log
2014-07-02 20:52:39.345 DEBUG className:200 - This is debug message
2014-07-02 20:52:39.366 DEBUG className:201 - This is debug message2
Convert dates snippet:
public static void main(String[] args) throws Exception {
String logdate = "2014-07-02 20:52:39.345";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
System.out.println(df.parse(logdate));
}
OUTPUT (Date::toString
!!!)
Wed Jul 02 20:52:39 CEST 2014

Jordi Castilla
- 26,609
- 8
- 70
- 109
-
Not sure how good that works when you have multi-threading and a lot of "interleaved" messages. – GhostCat Jul 04 '16 at 11:55
-
@Jägermeister exactly same as transforming log dates in milliseconds... – Jordi Castilla Jul 04 '16 at 11:57
0
You can provide a specific pattern layout in your log4j configuration file. Check this link for details regarding the different things you can include in the log4j log text.
If you want to get an idea of the time taken for a block of code to execute, you could try putting logging statements before and after that piece of code, and manually find the time difference to get to know the same.
This is not a conventional way, and I suggest you also try to work out why you are unable to attach a profiler.

Aditya Gupta
- 633
- 1
- 4
- 11