//log.c
- #include <log4c.h>
- #include <assert.h>
- #include "log.h"
- static log4c_category_t *log_category = NULL;
- int log_open(constchar *category)
- {
- if (log4c_init() == 1)
- {
- return -1;
- }
- log_category = log4c_category_get(category);
- return 0 ;
- }
- void log_message(int priority , constchar *fmt , ...)
- {
- va_list ap;
- assert(log_category != NULL);
- va_start(ap, fmt);
- log4c_category_vlog(log_category , priority , fmt , ap);
- va_end(ap);
- }
- void log_trace(constchar *file, int line, constchar *fun,
- constchar *fmt , ...)
- {
- char new_fmt[2048];
- constchar *head_fmt = "[file:%s, line:%d, function:%s]";
- va_list ap;
- int n;
- assert(log_category != NULL);
- n = sprintf(new_fmt, head_fmt , file , line , fun);
- strcat(new_fmt + n , fmt);
- va_start(ap , fmt);
- log4c_category_vlog(log_category , LOG4C_PRIORITY_TRACE, new_fmt , ap);
- va_end(ap);
- }
- int log_close()
- {
- return (log4c_fini());
- }
//test-log.c
- #include <stdio.h>
- #include "log.h"
- int main(void)
- {
- log_open("smartpipe_log");
- LOG_TRACE("trace");
- LOG_ERROR("error");
- LOG_WARN("warn");
- LOG_NOTICE("notice");
- LOG_DEBUG("hello log4c!");
- log_close();
- return 0;
- }
//配置文件,默认名为log4crc
- <?xmlversion="1.0"encoding="ISO-8859-1"?>
- <!DOCTYPE log4c SYSTEM "">
- <log4cversion="1.2.1">
- <config>
- <bufsize>0</bufsize>
- <debuglevel="2"/>
- <nocleanup>0</nocleanup>
- <reread>1</reread>
- </config>
- <!-- root category ========================================= -->
- <categoryname="root"priority="notice"/>
- <categoryname="mycat"priority="debug"appender="stdout"/>
- <!-- default appenders ===================================== -->
- <appendername="stdout"type="stream"layout="basic"/>
- <appendername="stderr"type="stream"layout="dated"/>
- <appendername="syslog"type="syslog"layout="basic"/>
- <!-- default layouts ======================================= -->
- <layoutname="basic"type="basic"/>
- <layoutname="dated"type="dated"/>
- </log4c>
编译命令:
gcc test-log.c log.c -o test-log -llog4c
运行效果
./test-log
[stdout] TRACE mycat - [file:test-log.c, line:7, function:main]trace
[stdout] ERROR mycat - error
[stdout] WARN mycat - warn
[stdout] NOTICE mycat - notice
[stdout] DEBUG mycat - hello log4c!
讲解:
关于log.h ,log.c封装的内容大家可以看看,用到了可变参数宏,可变参数这些。百度一下,就有很多人讲解了。这里就不说了。
log.h与log.c里面用法也很简单
log_open("category_name"); //category_name一定得是log4crc里面已经定义的category.
关于配置文件log4crc
更复杂的配置参见: http://www.linuxidc.com/Linux/2012-11/74331.htm
配置文件的搜索是由LOG4C_RCPATH环境变量决定。搜索的配置文件名为log4crc(不知道能否改变,没研究过)
配置文件中category的priority不知道是什么意思,,反正好像没什么用。不管设置成什么,好像都不影响。
环境变量:
LOG4C_RCPATH holds the path to the main log4crc configuration file #环境变量若未设置,则在工作目录(一般为运行目录)搜索log4crc配置文件. 如果设置了此变量,则所以用log4c库的程序都会使用此路径下的log4c配置文件(可根据category区分).
LOG4C_PRIORITY holds the "root" category priority #改变root的priority,,
LOG4C_APPENDER holds the "root" category appender #改变root的appender,,因为root默认没设置appender.
如果有什么问题,可以一起讨论下。若有什么错误,请各位指出。谢谢!
