Open System Services Programmer's Guide

Example 57 Use of System Logging Functions
/* Using System logging functions */
#include <fcntl.h>
#include <syslog.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
char *ident="Test X"; /* Identity string, "syslog" by default */
int logopt=LOG_CONS|LOG_PID|LOG_ODELAY; /* Logging options */
int facility=LOG_USER; /* Part of system generating event message */
int maskpri=LOG_UPTO(LOG_INFO); /* EMS event log mask */
char buf[512];
int fd;
/* Open the system log with the appropriate options
- identity string
- logging option
- generated by user program by default
*/
openlog(ident, logopt, facility);
/* Set the Event Management Service (EMS) event log mask */
setlogmask(maskpri);
/* Write a "Daemon X started" message. */
syslog(LOG_INFO, "Daemon X started.\n");
/* Make sure the correct number of arguments are entered
in starting up the daemon.
If not, print a usage message and exit. */
if(argc < 2) {
syslog(LOG_ERR, "Usage: syslog pathname\n");
exit (1);
}
/* If the file cannot be opened, log an error message and exit. */
if((fd = open(argv[1], O_RDONLY)) < 0) {
syslog(LOG_ERR, "Can't open %s\n", argv[1]);
exit(1);
}
/* If the file is not at least 512 bytes long, log a read error. */
if(read(fd, buf, 512) != 512) {
syslog(LOG_ERR, "Read error %m on key daemon file.\n");
exit(1);
}
close(fd);
/* Write a "Daemon X stopped" message. */
syslog(LOG_INFO,"Daemon X stopped.\n");
/* Close connection to EMS collector process */
closelog();
exit(0);
}
Closing a Collector
To close the connection to the EMS collector process opened by openlog() or syslog(), call
the closelog() function.
242 Using Logging Mechanisms