分享

syslog(),openlog(),closelog()

 點點滴滴 2011-01-09

syslog(),openlog(),closelog()

www.    时间 : 2007-09-18  作者:佚名   编辑:本站 点击:  870 



    这里面的三个函数openlog, syslog, closelog是一套系统日志写入接口。另外那个vsyslog和syslog功能一样,只是参数格式不同。
    通常,syslog守护进程读取三种格式的记录消息。此守护进程在启动时读一个配置文件。一般来说,其文件名为/etc/syslog.conf,该文件 决定了不同种类的消息应送向何处。例如,紧急消息可被送向系统管理员(若已登录),并在控制台上显示,而警告消息则可记录到一个文件中。该机制提供了 syslog函数,其调用格式如下
#include <syslog.h>
void openlog (char*ident,int option ,int facility);
void syslog(int priority,char*format,……)
void closelog();

    调用openlog是可选择的。如果不调用openlog,则在第一次调用syslog时,自动调用openlog。调用closelog也是可选择的, 它只是关闭被用于与syslog守护进程通信的描述符。调用openlog 使我们可以指定一个ident,以后, 此ident 将被加至每则记录消息中。ident 一般是程序的名称(例如 ,cron ,ine 等)


程序的用法示例代码如下:


#include <syslog.h>
int main(int argc, char **argv)
{
    openlog("MyMsgMARK", LOG_CONS | LOG_PID, 0);
    syslog(LOG_DEBUG,
           "This is a syslog test message generated by program '%s'\n",
           argv[0]);
    closelog();
    return 0;
}
 
编译生成可执行程序后,运行一次程序将向/var/log/message文件添加一行信息如下:
        Feb 12 08:48:38 localhost MyMsgMARK[7085]: This is a syslog test message generated by program './a.out'
 
openlog及closelog函数说明
此函数原型如下:
void openlog(const char *ident, int option, int facility);
此函数用来打开一个到系统日志记录程序的连接,打开之后就可以用syslog或vsyslog函数向系统日志里添加信息了。而closelog函数就是用来关闭此连接的。
openlog 的第一个参数ident将是一个标记,ident所表示的字符串将固定地加在每行日志的前面以标识这个日志,通常就写成当前程序的名称以作标记。第二个参 数option是下列值取与运算的结果:LOG_CONS, LOG_NDELAY, LOG_NOWAIT, LOG_ODELAY, LOG_PERROR, LOG_PID,各值意义请参考man openlog手册:
       LOG_CONS
              Write directly to system console if there is an error while sending to system logger.

       LOG_NDELAY
              Open the connection immediately (normally, the connection is opened when the first message is logged).

       LOG_NOWAIT
              Don’t  wait  for  child processes that may have been created while logging the message.  (The GNU C library does not create a
              child process, so this option has no effect on Linux.)

       LOG_ODELAY
              The converse of LOG_NDELAY; opening of the connection is delayed until syslog() is called.  (This is the  default,  and  need
              not be specified.)

       LOG_PERROR
              (Not in SUSv3.) Print to stderr as well.

       LOG_PID
              Include PID with each message.
 
第三个参数指明记录日志的程序的类型。

syslog函数及参数
syslog函数用于把日志消息发给系统程序syslogd去记录,此函数原型是:
void syslog(int priority, const char *format, ...);
第一个参数是消息的紧急级别,第二个参数是消息的格式,之后是格式对应的参数。就是printf函数一样使用。

如果我们的程序要使用系统日志功能,只需要在程序启动时使用openlog函数来连接syslogd程序,后面随时用syslog函数写日志就行了。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多