Friday, September 28, 2007
Adding timestamp to command output in Unix
Haven't you had the same irritating expression when you are trying to troubleshoot the performance problem in Unix and find out that vmstat command (and bunch of other commands) doesn't print the timestamp, leaving you in lurch to guess the probable time to which a line in vmstat maps to?
Same goes for JDK garbage collection log files (however JRockit provides a command line option to log timestamp along).
Well, there is simple way to do this using awk. Add the below variable and function addts (stands for "add timestamp") snippet to your .bash_profile (assuming you use bash or whichever place appropriate for your shell) and you have it handy whenever you want it.
export addtscmd='{now=strftime("[%b %d %Y %I:%M:%S %p] "); print now $0}' function addts { awk "${addtscmd}"; }
Here is an example of using vmstat before and after the timestamp.
vmstat without timestamp
[lbs@lsctlnx48 lbs]$ vmstat 1 5 procs memory swap io system cpu r b swpd free buff cache si so bi bo in cs us sy id wa 0 0 0 77396 173080 848712 0 0 5 3 3 3 2 1 2 2 0 0 0 77396 173080 848712 0 0 0 0 178 94 0 0 100 0 0 0 0 77396 173080 848712 0 0 0 0 115 106 0 0 100 0 0 0 0 77396 173080 848712 0 0 0 0 138 115 0 0 100 0 0 0 0 77396 173080 848712 0 0 0 0 105 95 0 0 100 0
vmstat with timestamp
[lbs@lsctlnx48 lbs]$ vmstat 1 5 | addts [Sep 28 2007 05:26:12 PM] procs memory swap io system cpu [Sep 28 2007 05:26:12 PM] r b swpd free buff cache si so bi bo in cs us sy id wa [Sep 28 2007 05:26:12 PM] 2 0 0 77380 173080 848712 0 0 5 3 3 3 2 1 2 2 [Sep 28 2007 05:26:13 PM] 0 0 0 77380 173080 848712 0 0 0 0 190 105 0 0 100 0 [Sep 28 2007 05:26:14 PM] 0 0 0 77380 173080 848712 0 0 0 0 159 113 0 0 100 0 [Sep 28 2007 05:26:15 PM] 0 0 0 77380 173080 848712 0 0 0 0 105 105 0 0 100 0 [Sep 28 2007 05:26:17 PM] 0 0 0 77380 173080 848712 0 0 0 30 111 124 0 0 94 6
The above command addts can be used with any tool output including tail -f. So it's as easy as it sounds to timestamp all garbage collection log files :)