[ Team LiB ] |
Recipe 9.32 Writing Log Entries via Shell Scripts9.32.1 ProblemYou want to add information to the system log using a shell script. 9.32.2 SolutionUse 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
9.32.3 DiscussionOur recipe shows how to use shell functions to implement the syslog API (see The syslog API) within shell scripts. The openlog function can be readily extended to recognize other, comma-separated options. The syslog function uses the same syntax as logger for the optional facility. The closelog function just restores the defaults for the identifier and facility, which are stored in global variables. These functions can be stored in a separate file and sourced by other shell scripts, as a convenient alternative to the direct use of logger. 9.32.4 See Also |
[ Team LiB ] |