1、zlog的下载、编译与安装
git clone https://github.com/HardySimpson/zlog.git
vim src/makefile
设置安装路径PREFIX
设置工具链CC
编译问题:
relocation R_X86_64_PC32 against symbol `zlog_conf_del'......recompile with –fPIC
解决方法:REAL_CFLAGS之前增加CFLAGS += -fPIC
make
make install
2、使用手册
http://hardysimpson.github.io/zlog/UsersGuide-CN.html
3、参考配置
[global]
strict init = true
reload conf period = 0
buffer min = 1024
buffer max = 2MB
rotate lock file = self
default format = "%d(%F %T.%l) %-6V (%c:%F:%L) - %m%n"
file perms = 666
fsync period = 1K
[levels]
#TRACE = 10
#CRIT = 130, LOG_CRIT
[formats]
simple = "%m%n"
normal = "%d [%V] [%U:%L] %m%n"
[rules]
test.* >stdout; normal
test_log.* "./test.log", 1KB*4 ~ "./test-%d(%Y%m%d).#2s.log"; normal
4、参考demo
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "zlog.h"
int main(int argc, const char *argv[])
{
int rc;
zlog_category_t *c;
rc = zlog_init("./zlog.conf");//初始化
if (rc)
{
printf("init failed\n");
return -1;
}
c = zlog_get_category("test_log");//获取test_log分类和对应的规则
if (!c)
{
printf("zlog_get_category failed\n");
zlog_fini();
return -2;
}
int i = 7;
zlog_info(c, "abcdecghilklmnopqrstuvwxyz:%d", i);//写日志
zlog_fini();//清理
return 0;
}
5、说明
[rules]
test_log.DEBUG "./test.log", 1KB*4 ~ "./test-%d(%Y%m%d).#2s.log"; normal
test_log:分类
DEBUG:日志等级
"./test.log", 1KB*4 ~ "./test-%d(%Y%m%d).#2s.log"; normal:具体规则
"./test.log":日志保存路径
1KB:每个日志文件的大小
4:最多保存4个日志文件
"./test-%d(%Y%m%d).#2s.log":文件转档设置(当日志文件满1KB时进行转档保存)
normal:设置的日志输出格式
6、zlog进阶
自定义输出
#include <stdio.h>
#include <stdlib.h>
#include "zlog.h"
#define ZLOG_CONFIG_PATH "./zlog.conf"
zlog_category_t *errorCat = NULL;
int zlogApi_Error(zlog_msg_t *msg)
{
printf("\033[40;31m");
//printf("[%s][%s][%ld]\n", msg->path, msg->buf, (long)msg->len);
printf("%s", msg->buf);
printf("\033[0m");
return 0;
}
int zlogApi_reload(void)//重载配置
{
return zlog_reload(ZLOG_CONFIG_PATH);
}
//signal(SIGUSR1, zlogApi_reloadSignalHandler);
//注册用户信号,用于重置配置
//kill -USR1 pid
void zlogApi_reloadSignalHandler(int sig)
{
//printf("reload signal:%d\n", sig);
zlogApi_reload();
}
int zlogApi_init(void)
{
int ret = 0;
ret = zlog_init(ZLOG_CONFIG_PATH);
if (ret)
{
printf("zlog_init failed\n");
return -1;
}
zlog_set_record("myError", zlogApi_Error);
errorCat = zlog_get_category("myErrorCat");
if (!errorCat)
{
printf("zlog_get_category errorCat failed\n");
zlog_fini();
return -2;
}
return 0;
}
void zlogApi_deInit(void)
{
zlog_fini();
}
#ifndef _ZLOG_API_H_
#define _ZLOG_API_H_
#include "zlog.h"
extern zlog_category_t *errorCat;
#define My_Zlog_Error(fmt...) zlog_error(errorCat, fmt)
int zlogApi_reload(void);
void zlogApi_reloadSignalHandler(int sig);
int zlogApi_init(void);
void zlogApi_deInit(void);
#endif
[formats]
simple = "%m%n"
format01 = "%d [%V] [%U:%L] %m%n"
format02 = "[%V] [%U:%L] %m%n"
[rules]
myErrorCat.* $myError, ""; format02
#myErrorCat.* "./my.log", 1KB*2 ~ "./my-%d(%Y%m%d).#2s.log"; format01
#myErrorCat.* "/dev/null"
#通过注释规则和重载配置来实现控制日志输出