Sceptersax
Sceptersax

Reputation: 83

Create a log of what's being sent by email in my script

This script currently monitors a log file for keywords. Upon discovery of said keywords, the script then produces a message pertaining to the state of a server (up or down). It then outputs an email directly to me. The rest of the script just kills the script after a predetermined period of time.

Finally, what I'd like to do now is send the same info being sent to email, to a log file: emailoutput > /var/log/server_mon.txt

I've tried to use the cat and exec command to direct the printed messages to a file, but my syntax is wrong every time. Not really a programmer and not sure how or where exactly to apply the command. my guess is somewhere after "print" but again, not sure how.

#!/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 [email protected] </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

Expected result is to have whats being output to email, to a text file for the purpose of keeping track of how often the script is reporting the servers condition.

I'm running this script on centos 5.5 btw..

Upvotes: 1

Views: 365

Answers (2)

Ed Morton
Ed Morton

Reputation: 203985

print msg | "cat>&2" is printing the message to stderr. Do you want to print it to /var/log/server_mon.txt instead of stderr or in addition to stderr?

There's a lot of options including:

awk '
    ...
    print msg | "cat>&2"
    print msg > "/var/log/server_mon.txt"
    ...
'

Remove print msg | "cat>&2" if you no longer need it.

or to get both with one print:

awk '
    ...
    print msg | "tee -a \047/var/log/server_mon.txt\047 >&2"
    ...
'

or:

awk '
    ...
    print msg
    ...
' | tee -a '/var/log/server_mon.txt' >&2

or:

awk '
    ...
    print msg | "cat>&2"
    ...
' 2> >(tee -a '/var/log/server_mon.txt' >&2)

So many options....

Upvotes: 1

Michael Back
Michael Back

Reputation: 1871

In your awk script make sure msg makes it to stdout:

print msg

Then outside your awk script add:

| tee -a /var/log/server_mon.txt

Upvotes: 1

Related Questions