1.zlog简述:
zlog是个概念清晰的日志函数库,在效率、功能、安全性上大大超过了log4c,并且是用c写成的,具有比较好的通用性。
log是一个高性能、线程安全、灵活、概念清晰的纯C日志函数库。
事实上,在C的世界里面没有特别好的日志函数库(就像JAVA里面的的log4j,或者C++的log4cxx)。C程序员都喜欢用自己的轮子。printf就是个挺好的轮子,但没办法通过配置改变日志的格式或者输出文件。syslog是个系统级别的轮子,不过速度慢,而且功能比较单调。log4c异常坑爹(有内存泄漏、效率低等等),而且已经停止开发
zlog有这些特性:
* syslog分类模型,基于规则路由过滤,比log4j模型要正确高效,详见为什么log4j的概念模型是错误的。
* 日志格式定制,类似于log4j的pattern layout
* 多种输出,包括动态文件、静态文件、stdout、stderr、syslog、用户自定义输出函数
* 运行时手动或自动刷新配置(同时保证安全)
* 高性能,在我的笔记本上达到338'638条日志每秒, 大概是syslog(3)配合rsyslogd的1000倍速度
* 高可靠性和速度之间的平衡,用户自定义多少条日志后fsync数据到硬盘
* 用户自定义等级
* 多线程和多进程环境下保证安全转档
* 精确到微秒
* 简单调用包装dzlog(一个程序默认只用一个分类)
* MDC,线程键-值对的表,可以扩展用户自定义的字段
* 自诊断,可以在运行时输出zlog自己的日志和配置状态
* 不依赖其他库,只要是个POSIX系统就成(当然还要一个C99兼容的vsnprintf)
2.使用
先下载:https://github.com/downloads/HardySimpson/zlog/zlog-latest-stable.tar.gz
解压安装:
zlog-latest-stable.tar.gz
$ tar -zxvf zlog-latest-stable.tar.gz
$ cd zlog-latest-stable/
$ make
$ sudo make install
or
$ sudo make PREFIX=/usr/local/ install
$ sudo vi /etc/ld.so.conf
/usr/local/lib
$ sudo ldconfig
#配置文件
$ cat /etc/zlog.conf
[formats]
simple = "%f:%L|%V: %m%n"
[rules]
my_cat.DEBUG >stdout; simple
3.示例
test_hello.c
#include <stdio.h>
#include "zlog.h"
int main(int argc, char** argv)
{
int rc;
zlog_category_t *c;
rc = zlog_init("/etc/zlog.conf");
if (rc) {
printf("init failed\n");
return -1;
}
c = zlog_get_category("my_cat");
if (!c) {
printf("get cat fail\n");
zlog_fini();
return -2;
}
zlog_info(c, "hello, zlog");
zlog_fini();
return 0;
}
makefile
INCS = -I/usr/local/include
CFLAGS = $(INCS) -L/usr/local/lib -lzlog -lpthread
test_hello:test_hello.o
gcc -o test_hello test_hello.o $(CFLAGS)
test_hello.o:test_hello.c
gcc $(INCS) -c -o $@ $<
clean:
rm test_hello.o test_hello
编译:
make
执行:
./test_hello
test_hello.c:23|INFO: hello, zlog