9.34. Writing Log Entries via C
Problem
You want to add information to the system log from a C program.
Solution
Use the system library functions
openlog
, syslog
, and
closelog
(see The syslog API):
syslog-demo.c:
#define _GNU_SOURCE /* for basename( ) in <string.h> */
#include <syslog.h>
#include <string.h>
int count = 0;
char *host = "some-machine
";
int main(int argc, char *argv[]) {
openlog(basename(argv[0]), LOG_PID, LOG_LOCAL3);
syslog(LOG_WARNING, "%d connection attempts from %s", count, host);
syslog(LOG_AUTHPRIV|LOG_ERR, "intruder alert!");
syslog(LOG_ERR, "can't open configuration file: %m");
closelog( );
return(0);
}
Discussion
Like Perl scripts [Recipe 9.33], C programs can pass
the %m
format specifier to
syslog
to include system
error messages, corresponding to
strerror(errno)
. Be sure to use
%m
only when a system error has occurred, to avoid
misleading messages.
See Also
syslog(3).
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.