August 2005
syslog Examples
Many other texts written here contain small examples of using the
syslog facility within scripts and programs.
Three very simple examples of using syslog in
C, Perl and a shell script are shown in this text.
logger Utility
One of the most powerful syslog tools available to the UNIX user
is the logger utility. Most experienced UNIX users are
well aware of the logger utility, however, it bears mentioning
simply because if you are not aware of it, it is a treat.
The logger utility is pretty straightforward, basically it can be used just with a message closed in quotes:
logger "Good morning Dave"
Of course, for it to be meaningful, it needs a context and a little more use of options.
Following; the UID of the person kicking out the message is sent using the -i option and it is sent to standard error (since it only logs on an error) specified by the -s option. The script simply looks for a mystical pidfile and kicks out an error message if it cannot find the file.
...
CHECK=/var/run/foo.pid
...
if [ -f $CHECK ]; then
echo Good
else
logger -i -s "${CHECK} not found"
fi
...
exit 0
It is worth noting that the logger man page is definitely worth a read. A great deal more can be done with the logger utility and it is by far one of the most powerful user utilities available.
The syslog facility is also available to Perl via a module, of course
the Sys::Syslog module. In the most basic form, syslog
is opened, the message plus any additional info is sent, then
it is closed.
In the following example, the facility is opened, the program name, PID and user are sent - then an info level message. Finally, it is closed:
...
use Sys::Syslog;
use Sys::Syslog qw(:DEFAULT setlogsock);
...
$program = "syslog.pl";
openlog($progam, 'pid', 'user');
syslog('info', 'started');
closelog();
...
Simple stuff, however, as per the norm there is much more than can be done. Visit CPAN for more information on syslog modules and how they can help out.
Syslog in C is interesting as one of the fields to the call has flags in it. Not unlike the Perl example, in C first the facility is opened, then messages are sent. Actually, it is nearly identical:
#include <syslog.h>
...
char *prog;
prog = "c_syslog";
openlog (prog, LOG_CONS | LOG_PID, LOG_LOCAL1);
syslog (LOG_NOTICE, "started by %d", getuid());
syslog (LOG_INFO, "That was fun");
closelog();
...
The C interface is interesting in that flags can be passed in the
openlog() portion for additional information logging.
The glibc manual has more details on different ways to use the syslog
interface.
Syslog is a great tool, however, many think that only root can use it. Such is not the case, not only can users use it on most systems, it can be a tremendous help when trying to centralize logging from shell programs to applications written in C. Rest assured, every other language that compiles or interprets on UNIX and UNIX-like systems support syslog - one way or the other.