#include <syslog.h> void openlog(char *ident, int option, int facility); void syslog(int priority, char *format, ...); void closelog();
其中openlog和closelog都是可选的。不过,通过调用openlog,我们可以指定ident参数。这样,ident将被加到每条日记记录中。ident一般设成程序的名字,如在下面例子中的"testsyslog":
#include <syslog.h> int main(int argc, char *argv[]) { openlog("testsyslog", LOG_CONS | LOG_PID, 0); syslog(LOG_USER | LOG_INFO, "syslog test message generated in program %s \n", argv[0]); closelog(); return 0; }
编译生成可执行文件后,每运行一次,程序将往/var/log/messages添加一条如下的记录:
Apr 23 17:15:15 lirong-920181 testsyslog[27214]: syslog test message generated in program ./a.out
格式基本是:timestamp hostname ident[pid]:log message。其中ident就是我们调用openlog是指定的"testsyslog",而之所以会打印出[27214]是openlog的option参数中指定了LOG_PID。下面我们详细讨论openlog函数中的option,facility和syslog函数中的priority参数。
根据/usr/include/sys/syslog.h文件,我们可以看到syslog支持的option如下:
/* * Option flags for openlog. * * LOG_ODELAY no longer does anything. * LOG_NDELAY is the inverse of what it used to be. */ #define LOG_PID 0x01 /* log the pid with each message */ #define LOG_CONS 0x02 /* log on the console if errors in sending */ #define LOG_ODELAY 0x04 /* delay open until first syslog() (default) */ #define LOG_NDELAY 0x08 /* don't delay open */ #define LOG_NOWAIT 0x10 /* don't wait for console forks: DEPRECATED */ #define LOG_PERROR 0x20 /* log to stderr as well */