Linux应用程序--syslog应用
文章摘要:
syslog常被称为系统日志或系统记录,在Linux守护进程中,经常需要打印一些调试信息至日志中,用于调试及问题排查,可以输出至syslog中,通过操作系统自带的日志功能来管理运行日志。
#include <stdio.h>
#include <stdarg.h>
#include <syslog.h>
// 输入格式化信息至日志文件
void glog(char *fmt, ...)
{
static int open = 0;
va_list ap;
char buff[4096];
if (open == 0)
{
openlog("[test]", LOG_CONS|LOG_PERROR, LOG_USER);
open = 1;
}
va_start(ap, fmt);
vsnprintf(buff, sizeof(buff), fmt, ap);
va_end(ap);
syslog(LOG_INFO, "%s", buff);
}
// 输入内存查看至日志
void glog_dump(unsigned char *buff, int cnt)
{
char logbuf[4096];
int sp = 0;
unsigned char *p = (unsigned char *)buff;
while (cnt--)
{
sp += snprintf(&logbuf[sp], sizeof(logbuf) - sp, "%02X ", *p++);
}
syslog(LOG_INFO, "%s", logbuf);
}
// 测试函数
int main(int argc, char** argv)
{
unsigned char idx = 0;
while(1)
{
glog("Hello World %d", idx++);
sleep(2);
}
return 0;
}
注意事项: syslog 不支持换行
查看日志:
$ sudo grep test /var/log/message
Dec 24 02:35:22 localhost [test]: Hello World 0
Dec 24 02:35:24 localhost [test]: Hello World 1
Dec 24 02:35:26 localhost [test]: Hello World 2
Dec 24 02:35:28 localhost [test]: Hello World 3
Dec 24 02:35:30 localhost [test]: Hello World 4
Dec 24 02:35:32 localhost [test]: Hello World 5