Chinaunix首页 | 论坛 | 博客
  • 博客访问: 29930621
  • 博文数量: 230
  • 博客积分: 2868
  • 博客等级: 少校
  • 技术积分: 2223
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-08 21:48
个人简介

Live & Learn

文章分类

全部博文(230)

文章存档

2022年(2)

2019年(5)

2018年(15)

2017年(42)

2016年(24)

2015年(13)

2014年(1)

2012年(5)

2011年(58)

2010年(56)

2009年(9)

我的朋友

分类: 嵌入式

2011-02-22 17:45:26

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

阅读(1501) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~