Skip to Content
Linux Security Cookbook
book

Linux Security Cookbook

by Daniel J. Barrett, Richard E. Silverman, Robert G. Byrnes
June 2003
Intermediate to advanced
336 pages
8h 54m
English
O'Reilly Media, Inc.
Content preview from Linux Security Cookbook

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).

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Linux Security Cookbook - Second Edition

Practical Linux Security Cookbook - Second Edition

Tajinder Kalsi
Mastering Linux Command Line

Mastering Linux Command Line

Coding Gears | Train Your Brain

Publisher Resources

ISBN: 0596003919Errata Page