9.32. Writing Log Entries via Shell Scripts

Problem

You want to add information to the system log using a shell script.

Solution

Use logger and this handy API, which emulates that of Perl and C:

               syslog-api.sh:
#!/bin/sh
ident="$USER"
facility="user"
openlog( ) {
        if [ $# -ne 3 ]
        then
                echo "usage: openlog ident option[,option,...] facility" 1>&2
                return 1
        fi
        ident="$1"
        local option="$2"
        facility="$3"
        case ",$option," in
                *,pid,*)            ident="$ident[$$]";;
        esac
}

syslog( ) {
        if [ $# -lt 2 ]
        then
                echo "usage: syslog [facility.]priority format ..." 1>&2
                return 1
        fi
        local priority="$1"
        local format="$2"
        shift 2
        case "$priority" in
                *.*)    ;;
                *)      priority="$facility.$priority";;
        esac
        printf "$format" "$@" | logger -t "$ident" -p "$priority"
}

closelog( ) {
        ident="$USER"
        facility="user"
}

To use the functions in a shell script:

#!/bin/sh
source syslog-api.sh
openlog `basename "$0"` pid local3
syslog warning "%d connections from %s" $count $host
syslog authpriv.err "intruder alert!"
closelog

Get Linux Security Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.