这两天,因为项目的需要研究了一把如何利用Linux syslog写日记,这里简单整理一下。本人使用的系统是RHEL 5.5。
System Logging
Linux日记系统由系统日志监控程序syslogd和内核日志监控程序klogd组成。从它们的命名可以看到,这两个监控程序都是守护程序(daemon),且都注册成了系统服务。换句话说,我们可以在目录/etc/init.d/下找到它们对应的执行程序,并通过service命令对它们进行启动,关闭,重启等操作。/etc/syslog.conf文件是Linux日记系统的配置文件。下面是本人/etc/syslog.conf文件内容:
# Log all kernel messages to the console.
# Logging much else clutters up the screen.
#kern.* /dev/console
# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none;cron.none /var/log/messages
# The authpriv file has restricted access.
authpriv.* /var/log/secure
# Log all the mail messages in one place.
mail.* -/var/log/maillog
# Log cron stuff
cron.* /var/log/cron
# Everybody gets emergency messages
*.emerg *
# Save news errors of level crit and higher in a special file.
uucp,news.crit /var/log/spooler
# Save boot messages also to boot.log
local7.* /var/log/boot.log
在对这个配置文件进行详细的解释之前,我们先看一下在Linux C编程中如何利用syslog进行日记。
syslog APIs
Linux C中提供一套系统日记写入接口,包括三个函数:openlog,syslog和closelog。下面是这三个函数的调用格式:
#include
voidopenlog(char*ident,intoption,intfacility);
voidsyslog(intpriority,char*format, ...);
voidcloselog();
其中openlog和closelog都是可选的。不过,通过调用openlog,我们www.linuxidc.com可以指定ident参数。这样,ident将被加到每条日记记录中。ident一般设成程序的名字,如在下面例子中的"testsyslog":
#include
intmain(intargc,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();
return0;
}
编译生成可执行文件后,每运行一次,程序将往/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 */