The script already logs the output to a file called "server_mon.txt. I would like to append a timestamp to each entry for the purpose of tracking server activity.
I now understand that standard AWK doesn't have an inherent time/date function that can easily be assigned to a variable. I attempted the following but didn't work for me:
tail -fn0 /var/log/user | /usr/bin/awk '
BEGIN {
str = "date +%Y-%m-%d";
str = | getline date;
close str;
The following is my full script so far:
#!/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
tail -fn0 /var/log/user | /usr/bin/awk '
/disconnect_tcp_conn/ { report("down") }
/daemon apps started/ { report("up") }
function report(curr_state, msg) {
if ( prev_state != curr_state ) {
msg = "Server is " curr_state
system("mail -s \047" msg "\047 mail@gmail.com </dev/null")
print msg | "cat>&2"
prev_state = curr_state
}
}
'
&
PID=$!
DIEAT=`expr $SECONDS + 58`
while [ -d /proc/$PID ] && [ "$SECONDS" -lt "$DIEAT" ]
do
sleep 1
done
[ -d /proc/$PID ] && kill "$PID"
wait
Expect to see a timestamp associated with each log entry to server_mon.txt.
Thanks
I highly recommend just reading and printing the timestanps already present in your log file but if that's not an option for some reson then here are you choices:
GUN awk:
$ awk 'BEGIN{ timestamp = strftime("%F %T"); print timestamp }'
2019-05-17 18:40:56
Any awk (much less efficient due to spawning a shell for every call to date
):
$ awk 'BEGIN{ cmd="date \"+%F %T\""; timestamp=( (cmd | getline line) > 0 ? line : "N/A"); print timestamp }'
2019-05-17 18:40:59
Put the code where you need to generate the timestamp, I just have it in the BEGIN section to demonstrate how to write the code to generate a timestamp and save it in a variable.