phamalda
phamalda

Reputation: 17

tail -f log file timestamp

Good afternoon. I have log file that gets populated throughout the day as a number of scripts run at various times. It's not a huge file but one problem is that the log entries do not have timestamps for time of entry.

This being the case, I typically log in to the server through a PuTTY session and run a tail -f on that log file so I can see that those scripts are beginning. What I'd like to do is alter my tail -f to include a timestamp for each item displayed to the screen. I have used the following:

tail -f scheduler_date '+%m%d%y'.log | sed s/^/$(date +%H:%M%_*)/

The problem here is that it uses the timestamp of the tail command, not the time each line enters the log file.

I have reviewed a few other cases to include the ones below but none that I've found provide precisely what I'm looking for. Any help would be appreciated.

How to pipe tail -f into awk

https://users.cs.cf.ac.uk/Dave.Marshall/PERL/node241.html

Upvotes: 1

Views: 3043

Answers (1)

EndlosSchleife
EndlosSchleife

Reputation: 597

tail -f "scheduler_$(date '+%m%d%y').log" | perl -pe 's/^/$_=qx(date +%T_); chomp; $_/e'

qx calls an external date +%T_ command. Its output is stored in variable $_. chomp removes a trailing linefeed character from $_. Then $_ is returned to become the substitution.

I assume the last % in your command is a typo and should be replaced with the seconds, so I wrote %T, which is an abbreveation for %H:%M:%S.

If performance matters, you can do without a new date process per line like this:

tail ... | perl -pe 'BEGIN { use POSIX "strftime" } s/^/strftime "%T_", localtime/e'

Upvotes: 1

Related Questions