跳到主要内容

Linux 日志管理

syslog 服务

在具体的使用前我们需要先了解日志服务的一个deamon——rsyslogd。

rsyslogd相比较于syslogd提供了更多的服务,在我使用的Ubuntu15.10下,也是自带了rsyslogd。

rsyslog为我们提供日志的服务。它像众多的deamon程序一样默默的提供着服务。

配置文件 /etc/rsyslog.conf

接口函数

三个函数openlog , syslog, closelog是一套系统日志写入接口。另外那个vsyslog和syslog功能一样,只是参数格式不同。 原理:通常,syslog守护进程读取三种格式的记录消息。此守护进程在启动时读一个配置文件。一般来说,其文件名为/etc/syslog.conf(注释:if you want to redirect log to other place,you need to change this),该文件决定了不同种类的消息应送向何处。例如,紧急消息可被送向系统管理员(若已登录),并在控制台上显示,而警告消息则可记录到一个文件中。

#include <syslog.h>

void openlog(const char *ident, int option, int facility);
void syslog(int priority, const char *format, ...);
void closelog(void);

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

示例

完整代码位于 syslog_example.c

#include <syslog.h>

int main(int argc, char **argv)
{
openlog("GetIoT", LOG_CONS | LOG_PID, 0);
syslog(LOG_DEBUG, "Syslog test message generated by '%s'/n", argv[0]);
closelog();
return 0;
}

编译运行

gcc syslog_example.c
./a.out

查找日志

$ cat /var/log/syslog | grep "GetIoT"
Jul 25 20:50:29 Latitude-3420 GetIoT[349887]: syslog test message generated by './a.out'/n
Jul 25 20:51:15 Latitude-3420 GetIoT[350715]: Syslog test message generated by './a.out'/n