syslog(),openlog(),closelog()

 这里面的三个函数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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值