歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> 利用Linux syslog寫日記

利用Linux syslog寫日記

日期:2017/2/28 16:16:49   编辑:Linux教程

這兩天,因為項目的需要研究了一把如何利用Linux syslog寫日記,這裡簡單整理一下。本人使用的系統是RHEL 5.5。

System Logging

Linux日記系統由系統日志監控程序syslogd和內核日志監控程序klogd組成。從它們的命名可以看到,這兩個監控程序都是守護程序(daemon),且都注冊成了系統服務。換句話說,我們可以在目錄/etc/init.d/下找到它們對應的執行程序,並通過service命令對它們進行啟動,關閉,重啟等操作。/etc/syslog.conf文件是Linux日記系統的配置文件。下面是本人/etc/syslog.conf文件內容:

  1. # Log all kernel messages to the console.
  2. # Logging much else clutters up the screen.
  3. #kern.* /dev/console
  4. # Log anything (except mail) of level info or higher.
  5. # Don't log private authentication messages!
  6. *.info;mail.none;authpriv.none;cron.none /var/log/messages
  7. # The authpriv file has restricted access.
  8. authpriv.* /var/log/secure
  9. # Log all the mail messages in one place.
  10. mail.* -/var/log/maillog
  11. # Log cron stuff
  12. cron.* /var/log/cron
  13. # Everybody gets emergency messages
  14. *.emerg *
  15. # Save news errors of level crit and higher in a special file.
  16. uucp,news.crit /var/log/spooler
  17. # Save boot messages also to boot.log
  18. local7.* /var/log/boot.log

在對這個配置文件進行詳細的解釋之前,我們先看一下在Linux C編程中如何利用syslog進行日記。

syslog APIs

Linux C中提供一套系統日記寫入接口,包括三個函數:openlog,syslog和closelog。下面是這三個函數的調用格式:

  1. #include <syslog.h>
  2. void openlog(char *ident, int option, int facility);
  3. void syslog(int priority, char *format, ...);
  4. void closelog();

其中openlog和closelog都是可選的。不過,通過調用openlog,我們www.linuxidc.com可以指定ident參數。這樣,ident將被加到每條日記記錄中。ident一般設成程序的名字,如在下面例子中的"testsyslog":

  1. #include <syslog.h>
  2. int main(int argc, char *argv[])
  3. {
  4. openlog("testsyslog", LOG_CONS | LOG_PID, 0);
  5. syslog(LOG_USER | LOG_INFO, "syslog test message generated in program %s \n", argv[0]);
  6. closelog();
  7. return 0;
  8. }

編譯生成可執行文件後,每運行一次,程序將往/var/log/messages添加一條如下的記錄:

  1. 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如下:

  1. /*
  2. * Option flags for openlog.
  3. *
  4. * LOG_ODELAY no longer does anything.
  5. * LOG_NDELAY is the inverse of what it used to be.
  6. */
  7. #define LOG_PID 0x01 /* log the pid with each message */
  8. #define LOG_CONS 0x02 /* log on the console if errors in sending */
  9. #define LOG_ODELAY 0x04 /* delay open until first syslog() (default) */
  10. #define LOG_NDELAY 0x08 /* don't delay open */
  11. #define LOG_NOWAIT 0x10 /* don't wait for console forks: DEPRECATED */
  12. #define LOG_PERROR 0x20 /* log to stderr as well */
Copyright © Linux教程網 All Rights Reserved